30 Mart 2021 Salı

Data Distribution Unit (DDU) Nedir

Giriş
Data Distribution Unit (DDU) Mission Computer (Görev Bilgisayarı) ile diğer cihazlar (peripherals) arasındaki haberleşmeyi sağlayan kısımdır. Şeklen şöyle




Böylece şu işlevler sağlanır
1. Yalıtım
Görev Bilgisayarı, çevre birimlerinden yalıtılır

2. Farklı Cihazlar
Görev Bilgisayarına farklı cinste ve tipte çevre birimleri takılabilir

3. Yedeklilik (Redundancy)
Çevre birimlerinin yedekli olması sağlanabilir. DDU bir "windowing" kuralı uygulayarak (örneğin sinyal gücü, cihazın kalitesi, kullanıcı tercihi vs) aynı bilgileri veren farklı cihazlar arasında birisini tercih eder ve Görev Bilgisayarına bu cihaza ait bilgiyi gönderir. Eğer cihaz bozulursa, DDU otomatik olarak yedek cihaza geçer. Böylece Görev Bilgisayarında bir bozulma olmaz.

Mimari
Aslında DDU ile yazılım mimarilerinden birisi olan Hexagonal Architecture veya diğer ismiyle "Ports and Adapters" birbirlerine bayağı benziyorlar. Aslında Hexagonal Architecture ise çok daha genel bir mimaridir. Herhangi bir yerde kullanılabilir.

Fakat DDU genellikle kapalı sistemlerde kullanılır. Bu kapalı sistem gemi, uçak, araba gibi yazılım ağırlıklı bir sistemdir.

Çevre Birimleri
DDU terminolojisinden içinde çevre birimlerle haberleşmeyi sağlayan kısma
 -Peripheral Interface Unit (PIU),
- System Interface Unit (SIU)
gibi bir isim verilir.

Data Distribution Unit Donanımı
DDU tercihen tek bir kutu şeklindedir. Çevre birimlerine çok farklı protokol ve kablolama ile bağlanırken, çekirdek tarafına çıkış veren arayüz standart ve çokça kullanılan bir şeydir.

Veri Yapısı
Veri yapısı 3 başlık altında toplanabilir. Eğer Domain Driven Design kullanıyorsak şöyle gruplarız

 Application Entities
1. PIU Entities
Bir PIU'dan gelen mesaj olduğu gibi, başka PIU'lara dağıtılır. 
2. Mission Computer Entities
Mission Computer'a gönderilecek kayıtlardır

Domain Entities
1. System Entities
Failover, SubsystemState, Simulation Message Generation gibi logic içeren bilgilerin tutulduğu kayıtlar
2. Summary Entities. Bazı sistemlerde buna Data Reduction deniliyor.
PIU'lardan bir sürü veri akar. Bazı önemli alanları birleştirerek ekranda göstermek veya log'lamak isteyebilirim.

Tasarım Kuralı
Bence bu tür yazılımlarda Command Pattern bayağı kullanışlı. 

1. Çevresel cihazdan gelen veri bir Command içinde işlenir. 
2. Command entity'lere sadece yazma işlemi yapar. Command hangi entity tipini güncelleyeceğini bilir.
Örneğin bir Command sadece PIU kayıdını güncellerken, bir başka Command PIU, Summary Entity, Mission Computer kayıtlarının hepsini güncelleyebilir.

3. Entity'lere Listener takılır. Güncellenen entity bilgisi ile ne yapılacağı Listener'ın bileceği şeydir.

Command yazma işleminde şu entity'lerden bir veya bir kaç tanesini günceller.

1. PIU Entity Güncelleme
PIU Entity değerini güncelleyebilir. Yeni veri Listener aracılığıyla diğer PIU'lara yayınlanır. Eğer gerekiyorsa Failover kayıtlarına bakılarak, cihaz seçili veya etkinse, Mission Computer kayıları da güncellenir.

2. System Entity Güncelleme
System Entity aynı işi yapan bir veya daha fazla alıcıdan kuvvetli olanın tercih edildiği değerleri içerir. Bazen cihazlar yedeklidir, bazen de farklı cihazların kesişen işlevleri vardır. Örneğin hız hem GPS hem de Hız Ölçer ile ölçülebilir. Bu cihazlar arasında bir önceliklendirme koymak isteyebilirim. Böylece eğer çalışıyorsa hızı önce GPS ile ölçerim, eğer çalışmıyorsa Hız Ölçeri  ile ölçmek isteyebilirim. 

Tercih etme işi aslında bence DDS'teki Ownership Qos kullanımına benziyor.

3. Mission Computer Entity Güncelleme
Bazı bilgiler de görev bilgisayarına gönderilir. Gönderilen bilgi muhtemelen birden fazla cihazın bilgisinin bileşimini içeren bir mesaj şeklinde olacaktır.

4. Summary Entity Güncelleme
PIU'dan gelen bir sürü mesajı özet şeklinde ekranda gösterme veya loglama amacıyla kullanılır. Bu entity'ye takılan Listener gerekli işlemi gerçekleştirir.

Sınıf ve Mesaj İsimlendirme
DDU boru şeklinde olmasına rağmen çok katmanlı olabilir. Bu durumda sınıf isimlendirmesi önem kazanıyor.


Mesaj İsimleri
Mesaj isimleri XFromSensor, YToSensor şeklinde olabilir.

Konfigürasyon
Aynı tipte alıcılardan birden fazla varsa, her XFromSensor mesajına sourceDevice diye bir alan eklenebilir

DDU Int Bileşeni - Receive
network -> XFromSensorTopic -> XFromSensorTopicCommand -> XFromSensorTopicDTO

Yani : XFromSensorTopic okuyorsa ve DTO gönderiyorsa, command olarak XFromSensorTopicCommand çalıştırır. Burada DTO'ya dönüşüm olmasına rağmen önemsiz olduğu için command isminde belirtilmiyor.

DDU Core Bileşeni
XFromSensorTopicDTO -> XFromSensorCommand -> XRecordListener -> XRecordToSensorDTO

Yani : XFromSensorTopicDTO okuyorsa, command olarak XFromSensorCommand çalıştırır. Burada command ismi artık Topic, gibi şeyleri içermez, çünkü core işlemi yapmaktadır.

DDU Int Bileşeni - Send
XRecordToSensorDTO -> XRecordToSensorTopicCommand -> network

Yani : XRecordToSensorDTO okuyorsa ve topic gönderiyorsa, command olarak XRecordToSensorTopicCommand çalıştırır. Burada DTO'dan tekrar Topic'e dönüşüm olduğu için command isminde belirtiliyor.

29 Mart 2021 Pazartesi

OLTP vs OLAP

Giriş
Veri tabanları iki farklı iş için tasarlanır. Açıklaması şöyle
As you probably know, databases are divided into two types: Online Transactional Processing (OLTP) and Online Analytical Processing (OLAP).
Bu ikisinin farklılıklar şöyle
OLTP and OLAP describe two very different data processing methods, and, therefore, they have different database requirements.

Characteristics OLTP OLAP
Data queried in one request Small (a few rows) Large
Real-time update         Yes         No
Transactions         Yes         No
Concurrency         High         Low
Query pattern         Similar Varies a lot
1. OLTP
Açıklaması şöyle
Years ago, databases made little distinction between OLTP and OLAP. Instead, one database processed both types of requests. However, as the data volume grew, it became difficult to process two types of workloads in a single database. Most significantly, the different workload types interfered with each other.

Thus, to meet the special needs of OLAP workloads, people designed a separate database that only processed OLAP workloads. They exported data from OLTP databases to OLAP databases, and processed the OLAP workloads there. Separating the OLTP and OLAP workloads resolved the conflicts between the two workloads, but it also introduced external data replication. During the replication, it was hard to ensure that data was consistent and in real time.
2. OLAP - Eski/Arşiv Veri
OLAP eski ve arşiv veriyle uğraşır. Transaction miktarı azdır ve daha çok sorgu yapar. Sorgular karmaşıktır ve aggregation miktarı çoktur.

OLAP ismindeki online eskiden kalan bir kelime. Açıklaması şöyle
It is simply a remnant of olden times, when it was used in contrast to batch processing. "Online" here means "interactive", that is, requests to the database are processed as they come and responses are given more or less immediately, or at least as soon as they are available. Batch processing would collect requests into, well, batches, and execute them on schedule; responses would be given after the entire batch execution (e.g. next morning).
Örnek
Bir örnek şöyle
PostGre is usually used in OLTP scenarios with a bit of OLAP.
That is fine as long as you understand the difference between them.
For example, if a public-facing endpoint contains a very complex query that loads a lot of data and does complex operations, it’s probably a good indicator that it should be treated as OLAP and that endpoint refactored to adopt a different strategy.
Örnek
Açıklaması şöyle
Redshift supports some SQL functions and queries which would generally only be necessary with large data warehouse applications. For example, PERCENTILE_CONT computes a linear interpolation to return a percentile.
Şöyle yaparız
SELECT
    TOP 10 salesid,
    sum(pricepaid),
    percentile_cont(0.6) WITHIN GROUP (
        ORDER BY 
            salesid
    ),
    median (salesid)
FROM
    sales
GROUP BY
    salesid,
    pricepaid;
Örnek
OLAP veri tabanlarında one-to-many olması beklenen ilişkiler bile çok fazla normalize edilmiş olabilir.
Normalization Nedir yazısına bakabilirsiniz.

Aşağıdaki örnekte User, Department isimli iki farlı tablo var. Daha sonra bu iki farklı tabloyu birleştiren UserDepartmentTable tablosu var.

UsersTable
UserID  FirstName   LastName
234     John        Doe
516     Jane        Doe
123     Foo         Bar
DepartmentsTable
DepartmentID   Name
1              Sales
2              HR
3              IT
UserDepartmentTable
UserDepartmentID   UserID   Department
1                  234      2
2                  516      2
3                  123      1
RequestTable
RequestID   UserID   <...>
1           516      blah
2           516      blah
3           234      blah


26 Mart 2021 Cuma

Reactive Programlama Nedir?

Reactive Programlama Nedir?
Korkmayın nükleer teknoloji ile alakası yok :) Ancak plaza İngilizcesiyle artık her yerde karşımıza çıkan bir “hot topic”.

Not : LMAX tarafından geliştirilen Distruptor Reactive Programlamaya bir başka seçenek. Bir örnek burada

Okudum Ama Anlamadım
Evet yazılım dünyasının derdi bu zaten. Okuyup anlayamamak :) Anlamlı kelimeleri yan yana dizince anlaşılmaz cümleler nasıl ortaya çıkıyor bilmiyorum.

Observable, Observers, Schedulers, Flux, Mono, Backpressure vs. kavramları. Hiyeroglif gibi çizilmiş, bakanı kör eden “Marble Diagram” şekilleri. Geçelim.

Yani ?
Reactive Programlamada önemli iki şey var.
1. Komuta cevap vermek
2. İşlemciyi sürekli meşgul tutmak

Yani  asynchronous, non-blocking, event-driven, vıdı vıdı kelimelerinin özü bu iki madde. Bu iki maddenin önem sırası sizin geliştirme yaptığınız dünyaya göre değişebiliyor. 

Yani mobile ve backend dünyalarında farklı şeyler ifade ediyorlar.

Diyelim ki elimize telefonu aldık, bir uygulama çalıştırdık. Sonra telefonu yan döndürdüm. Ne olmasını beklerim ? Telefon “döndür/rotate” diye bir event yayınlasın. Benim sevgili uygulamam da bunu dinlesin ve hemen (yani non-blocking şekilde) kendisini döndürsün.

Uygulamayı kapatmaya karar verdim. O zaman hemen kapansın. Beni bekletmesin, acelem var :) Hani bazen Windows’ta bir işleme başlarsın ve iptal edemezsin ya. Bu olmasın  işte :)

Bu telefon dünyasının (dükkan ismiyle alakası yoktur) bakış açısı. 

Veya cloud üzerinde çalışan bir uygulamam olsun ve bana sürekli veri aksın. Bu veriyi  işlemek için 100 thread açayım. Yani “I/O bound” işlemler bolca var. Bu thread’ler için mutlaka context switch olacaktır, hatta daha kötüsü birisi ötekini bekletecektir, ve ben bu boşa geçen sürenin parasını bulut sağlayıcısına ödeyeceğim. Zengin miyim ? Değilim :) O zaman 4 thread açsam ve bunları sürekli meşgul tutsam nasıl olur? Bunun için her şeyi  asynchronous,  non-blocking yapmam lazım. Veri tabanına bağlantı mı açacağım? Ben işlemi başlatayım, sonra başka bir işe geçeyim. Sonucu işletim sistemi bana söylesin. 

Bu aslında aynı yemek pişirmeye benziyor. Ne kadar çok işi paralel yaparsam o kadar   hızlı biter. 

Reactive programlama çok daha fazlası aslında ancak birisi bana kısaca özetle derse bunları söylerdim. 

22 Mart 2021 Pazartesi

HTTP Durum Kodları - 1XX Informational Kodları

100 Continue
Sanırım büyük dosyaları upload ederken kullanılır.

101 Switching Protocols
Açıklaması şöyle
The correct status code to use here is without a doubt 301 Moved Permanently.

101 Switching Protocols is an internal status code that a server generally uses to automatically negotiate certain types of connections. It's not used when changing the URL from http to https. If you're curious about how it works, you can read about the 101 status code and the protocol upgrade mechanism on MDN, but you'll never need to know about it as a webmaster.

As a general rule, you should never directly use 100 or 200 series status codes unless you are actually developing web server software. The 300 and 400 series codes (especially 301, 302, and 404) are the ones you'll want to pay attention to when running a simple website.
102 Processing
Açıklaması şöyle. Sanırım uzun süren işlemlerde kullanılır.
The 102 (Processing) status code is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it. This status code SHOULD only be sent when the server has a reasonable expectation that the request will take significant time to complete. As  guidance, if a method is taking longer than 20 seconds (a reasonable, but arbitrary value) to process the server SHOULD return a 102 (Processing) response. The server MUST send a final response after the request has been completed.
Methods can potentially take a long period of time to process, especially methods that support the Depth header. In such cases the client may time-out the connection while waiting for a response. To prevent this the server may return a 102 (Processing) status code to indicate to the client that the server is still processing the method.
103 Early Hints
Açıklaması şöyle
Normally, when the browser sends a request, the server will receive it and process the request in less than a second and send an HTTP 200 OK response ...

Using the HTTP 103 Early Hints, however, there is room to improve the page rendering speed.

Once the server is updated with the HTTP 103 feature, when a browser sends a request, if the server knows that the content needs resources like style.css, script.js, and so on, then it will hint (respond) with the HTTP 103 Early Hints response to the browser to preload the content ...

Then, once the server processed the complete response, it will send normal HTTP 200 OK to the browser.

This process will help in the page rendering speed as the browser preloads the content ahead.

HTTP Durum Kodları - 2XX SUCCESS Kodları

Giriş
Açıklaması şöyle.
The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted.
200 - OK
Açıklaması şöyle.
200 means the server experienced no problems and has a representation of the results for the client to consume.
Sunucudaki bir dosyaya GET isteği gönderdiğimizi varsayalım. Cevap olarak 200 ile başlayan bir satır almamız tüm dosyayı indirdiğimiz anlamına gelmez. Http isteği bir bütün olarak düşünülmeli. Açıklaması şöyle.
HTTP 200 is generated by the server, and only means that it understood the request and thinks it is able to fulfill it (e.g. the file is actually there). All sorts of errors may occur during the transmission of the full response document (network connection breaking, packet loss, etc) which will not show up in the HTTP response, but need to be detected separately.
201 Created
Açıklaması şöyle. PUT isteği ile bir resource ilk defa yaratılırsa bu cevap döner.
If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response. If the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server MUST send either a 200 (OK) or a 204 (No Content) response to indicate successful completion of the request.
202 Accepted - Async taskİsteğin alındığını belirtir. 200'den farkı gönderilen isteğin daha sonra asenkron olarak işleneceğini ifade etmesidir.

Örnek
Açıklaması şöyle
Assume that your web/mobile application UI accepts a task request from a user, such as uploading an image or creating a profile. The backend will take considerable time to process the task, which can’t be completed within the scope of an HTTP request.

The typical pattern is that the backend accepts the request, validates it, and returns HTTP 202 status to the UI, denoting that the task has been accepted for processing. 

203 - Non-Authoritative Information (since HTTP/1.1)
Açıklaması şöyle.
203 means that the response was modified between the authoritative server and the client. 
204 - No Content
Client tarafından gönderilen isteğe "No Result" gibi bir cevap vermek istersek kullanılabilir. Rest servisini normalde vereceği cevap şöyle olsun.
{
  "results": [
    {
      "name": "Pancakes",
      ....
    },
    {
      "name": "French Fries",
      ....
    }
  ]
}
Ancak dönülen cevap boş ise 204 ve şöyle bir cevap gönderilebilir.
{
  "results": []
}
205 - Reset Content
Örnek ver

206 - Partial Content
Açıklaması şöyle.
206 appears to be designed for returning a large resource over multiple responses. It also requires that the client ask for a part of the content in the headers (so pagination via query strings does not qualify).
207 Multi-Status
Açıklaması şöyle. Birden fazla işin sonucu dönüleceği zaman kullanılabilir.
A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. The default Multi-Status response body is a text/xml or application/xml HTTP entity with a 'multistatus' root element. Further elements contain 200, 300, 400, and 500 series status codes generated during the method invocation. 100 series status codes SHOULD NOT be recorded in a 'response' XML element.
Although '207' is used as the overall response status code, the recipient needs to consult the contents of the multistatus response body for further information about the success or failure of the method execution. The response MAY be used in success, partial success and also in failure situations.

HTTP Durum Kodları - 3XX REDIRECTION Kodları

Giriş
Redirection yerine HSTS kullanılabilir. Açıklaması şöyle.
If a user try to access some random http://example.com, HSTS will transform the request into https://example.com, however the website need to have a valid certificate in order to function properly.
300 Multiple Choices
Örnek ver

301 Moved Permanently
Örnek ver

302 Found (Previously "Moved temporarily")
302 ile tarayıcıyı başka sayfaya yönlendirebilmek mümkün. 302 kodu ile beraber yönlendirilen URL bilgisini de göndermek gerekir. 302 cevabı şöyledir.
$ curl -I https://google.net/
HTTP/1.1 302 Found
Location: https://www.google.com/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
...
Örnek
302 durum kodu URL Shortening servisleri tarafından kullanılır.

Örnek
Wicket ile 302 göndermek için exception atılıyor. Örneğin RestartResponseException veya RedirectToUrlException ile bu gerçekleştirilebiliyor.

Eğer orijinal sayfaya tekrar dönülmesi gerekiyorsa RestartResponseAtInterceptPageException  kullanılıyor.

303 See Other
Örnek ver

304 Not Modified
Örnek ver

305 Use Proxy
Örnek ver

307 Temporary Redirect
Örnek ver

11 Mart 2021 Perşembe

NGINX - nginx.conf Dosyası - Limit Request

Giriş
Açıklaması şöyle
If the requests rate exceeds the rate configured for a zone, their processing is delayed such that requests are processed at a defined rate. Excessive requests are delayed until their number exceeds the maximum burst size in which case the request is terminated with an error. By default, the maximum burst size is equal to zero
Örnek
Şöyle yaparız
limit_req_zone $server_name zone=one:10m rate=100r/s;

server {
    location /search/ {
        limit_req zone=one burst=200;
    }
  ...
}

10 Mart 2021 Çarşamba

Change Data Capture

Giriş 
Bir veri tabanında yapılan değişikliğin bir başka veri tabanına aktarılmasını amaçlar. Açıklaması şöyle
Change Data Capture (CDC) is a design pattern focused on data integration. The CDC design pattern is quite simple: take every data change committed to a data source and publish it as an event.
CDC şu mimarilerde işe yarar

Eleştiriler
Açıklaması şöyle
... Even though CDC is a good start to moving toward event-driven architecture, it can not be a final stop. There are major challenges with it.

- CDC ties together the application database schema with the rest of the consumers. Application databases developers should be free to modify their databases without impacting any downstream consumers. CDC blocks that in a major way. When we do not allow other microservices to directly connect to databases but through APIs, how can we think the change in the stream of databases is OK for others to depend on?

- It can create major data quality issues because producers can make backward-incompatible changes without notifying consumers.

- Data domain could be very different from what you publish for the rest of the company to consume. CDC ties all downstream users to that schema 

Change Data Capture vs Event Carried State Transfer
Event Carried State Transfer için açıklama şöyle. Aslında amaç aynı. Bir veri tabanında değişiklik olunca diğerine yansıtmak. Kullanılan yöntem farklı. CDC de değişikliği yakalayan ve Kafka gibi bir broker'a yazan bir araç var. Event Carried State Transfer de ise bu işi micro service kodu yapıyor.
The idea behind Event Carried State Transfer pattern is — when a Microservice inserts/modifies/deletes data, it raises an event along with data. So the interested Microservices should consume the event and update their own copy of data accordingly.

CDC Event Yapısı
Örnek
Şöyle olabilir. Burada verinin before ve after halleri görülebilir.
{
  "schema": {...},
  "payload": {
    "before": {  
      "id": 1004,
      "first_name": "Anne Marie",
      "last_name": "Kretchmar",
      "email": "annek@noanswer.org"
    },
    "after": null,  
    "source": {  
      "name": "1.4.1.Final",
      "name": "dbserver1",
      "server_id": 223344,
      "ts_sec": 1486501558,
      "gtid": null,
      "file": "mysql-bin.000003",
      "pos": 725,
      "row": 0,
      "snapshot": null,
      "thread": 3,
      "db": "inventory",
      "table": "customers"
    },
    "op": "d",  
    "ts_ms": 1486501558315  
  }
}
CDC Araçları
Açıklaması şöyle. Önemli araçlar Debezium ve Kafka Connect
Database vendors provide a log scrapping system for popular databases. These are combined with the CDC tools to enable source and destination connectors. Two popular choices are Debezium and Kafka Connect. Kafka Connect provides support for large number of “source” and “sink” connectors.

Cloud databases provide this pattern as a managed cloud-native service. For example AWS Dynamo Streams ( Supported by AWS Kinesis Data Stream).

This pattern is also captured in the microservices Transaction Outbox pattern & Transaction Log Tailing pattern.

Frameworks like Axon & Eventuate provide support for this pattern.
Debezium
Debezium yazısına taşıdım

Yazılım Mimarisi - Microservice Mimarisinin Zorlukları

Giriş
Microservice mimarisi Hype Cycle'da "Trough of Disillusionment" kısmına yavaş yavaş geliyor. Açıklaması şöyle
Developers around the world are on a move to break down their monoliths into microservices. And they base this move on false assumptions. We already have many companies moving out of microservices back to monoliths. Microservices are now at the “Trough of Disillusionment”, in the Gartner Hype cycle.
Peki nerede Hype Cycle'da nerede olduğumuza bakmaksızın, bu mimarinin zorlukları nedir?

1. Microservice Mimarisinin Zorlukları
1.1 Yazılım Daha Karmaşık Hale Geliyor
Microservice mimari yazılımı daha karmaşık hale getiriyor. Açıklaması şöyle.
Microservices are generally undesirable because they turn your software into a distributed system – and distributed systems make everything a lot more difficult. But a service-oriented architecture has some important benefits:

- different services can be developed and deployed independently by different teams
- different services can be scaled independently
Bir başka açıklama şöyle.
...microservices introduce substantial complexity of their own, in addition to the base complexity of your system. You have to pay this “premium” in terms of reduced productivity. This means that for simple projects, microservices make you less productive. This changes for more complex projects: whereas a monolithic solution might become increasingly difficult to work with, a microservice architecture scales much better and requires roughly constant effort. You have to know whether the extra initial effort of microservices is worth it given your software system. Since you are asking this question, the answer is probably “no”.
Açıklaması şöyle.
Microservice architectures are certainly not without their own challenges, especially if you consider the explosion in independently moving parts it will give you. What you need to look out for, however, is focusing on the technicalities of it. Remember, just as SOA was about organizational structure rather than tools and standard protocols, microservices are about business agility rather than – again – tools and standard protocols.
1.2 Toplam Reliability Azalır
Uygulamanın toplam Reliability seviyesi yani Güvenilirlik seviyesi azalır. Açıklaması şöyle.
In the monolithic bare-metal application, if the server has an issue, be it network, hard drive, memory, or otherwise, the whole application goes down. So, if your provider gave you a 99.5% uptime guarantee, then you are confident of being up 99.5% of the time, however, with the microservice architecture, each component has its own uptime guarantee. So, if your application uses 10 services, each with 99.5% guarantee, then you now have 99.5% to the power of 10 = 95.0%.
2. Bazı Yanılsamalar
Microservice mimarisi ölçeklenebilir, kolay idame ettirilebilir, küçük ve dirençli yazılımlardır varsayımı aslında yanılsamalarla dolu.  Bazı yanılsamalar şöyle
Only microservices are scalable: FALSE. There are no metrics or methods that can be used to classify a code base as microservice or monolith. Even a 2 pizza team can be responsible by a monolith or by a microservice. It’s possible to scale both of them.

Only microservices code are easy to maintain: FALSE. If you have 5 developers responsible for a microservice, it’s already hard to reason about. It’s large, huge. If you call it a microservice or a monolith, it doesn’t matter. The number of lines of code are the same. You can organize your monolith into small modules so they can be easy to understand.

Microservices are small: FALSE. The word “micro” is misleading. Of course you can have a small microservice, but the recommendation is that microservices should not be so small that one developer can handle it alone. You’re only adding complexity and cost doing that. And again, you can have small and independent modules in your monolith.

Microservices are resilient: FALSE. Resilience is a matter of how you organize your modules or microservices and how they can still work on the presence of errors. You can have truly independent modules in a monolith that will work flawless or have 2 microservice bound by an HTTP call where it will only work when both are online only. Microservices are a distributed system, with a lot of moving parts. It’s much harder for it to be resilient than of a monolith.
3. Ne Zaman Microservice Kullanmalı
Tek parça (Monolith) yazılımın idamesi çok zor hale gelince düşünülebilir. Yani temel kural şöyle
Only add complexity when it solves problems you actually have
Açıklaması şöyle.
So my primary guideline would be don't even consider microservices unless you have a system that's too complex to manage as a monolith. The majority of software systems should be built as a single monolithic application. Do pay attention to good modularity within that monolith, but don't try to separate it into separate services.
Netflix örneği şöyle. Eğer 100 kişi aynı anda tek bir ürün üzerinde çalışamıyorsa, microservice mimarisi kullanılabilir.
Take for example the company that started all that: Netflix. They have one big product. One. How could be possible for 100 developers to work on the same git repository or code base? It’s fiscally impossible. That’s why they did it. And that is the only reason to use microservices.
4. Microservice İçin Gerekli Koşullar Sağlanmıyorsa
Açıklaması şöyle
For all the rest of us enterprise software developers, we should be writing monoliths. But not any monolith, a modular monolith. We want all the benefits microservices claims to provide within our monoliths.
Bu monolith içinde
1. Asenkron haberleşme için bir Message Broker olabilir
2. Şifreleri saklayan bir Security Vault olabilir
3. Yalıtılmış Containerlar olabilir.

5. Peki Ölçeklenedirme Ne Olacak?
Açıklaması şöyle. Yani önce vertical scalability seçeneği sonuna kadar kullanılmalı. Eğer direkt horizontal scalability seçeneği ile başlarsa, zaten bize gereken tüm kaynakları sadece Kubernetes gibi bir altyapıya harcıyoruz.
Enterprise software doesn’t require huge amounts of hardware. If your application will have 10000 concurrent users, one server is enough. Actually, it’s very affordable (in enterprise standards) at Amazon an EC2 machine with 40 cores and 128GB of RAM. So, you can vertically scale your applications a lot. That’s probably the total hardware of a complete kubernetes cluster that you would use to scale your application horizontally, but wasting memory on each replica server runtime. Which makes no sense, since application servers runs on top of the JVM. 

Apache Ignite - Distributed SQL ve Cache

Giriş
Açıklaması şöyle. Apache Ignite Java ile geliştirilmiş
Apache® Ignite™ was originally contributed to the Apache Software Foundation by GridGain Systems. The project rapidly evolved into a top level Apache project with tens of thousands of downloads per month. The GridGain Professional Edition, Enterprise Edition, and Ultimate Edition are built on Apache Ignite.
GridGain vs Apache Ignite
Açıklaması şöyle
Indeed, Gridgain is wraper built on top of Ignite. Gridgain gives you additional features such as Security, Rolling production update etc that is required for enterprise level application.
GridGain şirketi "Data Center Replication" da sunuyor

Neleri Destekler
Apache Ignite bir sürü şeyi birden destekliyor.
SQL
Key/Value
Transactions
Compute
Services
Streaming
Machine Learning
 Açıklaması şöyle
Apache Ignite is a high-performance distributed database that stores data in memory (as well as persistent).
As with every NoSQL solution, it supports replication and sharding out-of-the-box but also provides ACID transactions, SQL support, and Compute Grid.
Distributed SQL
Şeklen şöyle

Persistence
Ignite native persistence
Third party persistence

Durable Memory
Şeklen şöyle. Bir anlamnda Linux'taki swap dosya sistemine benziyor.


Maven
Şu satırı dahil ederiz
<properties>
  <ignite.version>2.10.0</ignite.version>
  <ignite.spring.data.version>1.0.0</ignite.spring.data.version>
</properties>

<dependency>
  <groupId>org.apache.ignite</groupId>
  <artifactId>ignite-core</artifactId>
  <version>${ignite.version}</version>
</dependency>

<dependency>
  <groupId>org.apache.ignite</groupId>
  <artifactId>ignite-spring</artifactId>
  <version>${ignite.version}</version>
</dependency>

<dependency>
  <groupId>org.apache.ignite</groupId>
  <artifactId>ignite-spring-data-2.2-ext</artifactId>
  <version>${ignite.spring.data.version}</version>
</dependency>
Örnekler
Gridgain örnekler burada
Bazı diğer örnekler burada

Bağlantı
Bağlantı için 3 yöntem var
1. Thick Client : Cluster topolojisine dahil olur
2. Thin Client : Cluster topolojisine dahil olmaz
3. JDBC : Relational Database olarak kullanmak istersek

Java
Şöyle yaparız. Herhangi bir düğüme bağlanmak yeterli
Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
Connection con = DriverManager.getConnection("jdbc:ignite:thin://192.168.0.50");
In-memory data grid
Apache Ignite in-memory data grid özelliğine sahip olduğu için Hazelcast gibi Distributed Cache olarak kullanılabilir.

Embedded node
Apache Ignite embedded olarak yani aynı JVM içinde kullanılabiliyor. Eğer Spring ile birlikte kullanmak istersek açıklaması şöyle
The embedded node can be started by SpringCacheManager itself. In this case, we will need to provide a path to either the Ignite configuration XML file or IgniteConfiguration bean via configurationPath or configuration properties respectively.
Ignite Rest API
Açıklaması şöyle
Ignite provides an out-of-the-box HTTP REST client that gives us the ability to communicate with the grid over HTTP and HTTPS protocols using the REST approach. REST APIs can be used to perform different operations like reading/writing from/to cache, execute tasks, get various metrics and more.

To enable HTTP connectivity, we have addedignite-rest-http as a Maven dependency in our application. Explicit configuration is not required; the connector starts up automatically and listens on port 8080. We can also change the port by specifying -DIGNITE_JETTY_PORT=8081 as VM arguments.

We can check whether the rest API is working by using the below curl command.
curl 'http://localhost:8081/ignite?cmd=version'

Following is a sample GET REST API which we can be used to procure the data from the Cache using the CacheName and key.
http://localhost:8081/ignite?cmd=get&cacheName=student&key=1
Anotasyonlar
@QuerySqlField
 Alanın Ignıte tarafından görülebilmesini sağlar

@AffinityKeyMapped
Foreign key olarak bağlı iki tablonun collocated olmasını sağlar. Satır sayısı az olduğu için Collocated yapılamayan tablolar, replicate edilmeli

SQL Dili
ANSI 99 uyumlu
INSERT 
UPDATE
DELETE
CREATE TABLE
DROP TABLE
CREATE INDEX
DROP INDEX
ALTER TABLE
SELECT : JOIN ve SUBQUERY 

yapılabilir

ALTER TABLE
Şöyle yaparız
ALTER TABLE city ADD COLUMN IF NOT EXISTS population int;
ALTER TABLE person DROP COLUMN (code,gdp);
CREATE INDEX
B+ Tree Index kullanır. Inline veri büyülüğü belirtilebilir.

CREATE TABLE
CREATE TABLE yazısına taşıdım

SELECT
Örnek
Şöyle yaparız. country ve city diye iki tablo var. Burada "Collocated Join"  önemli. Collocated yan yana demek. Non-collocated join'ler ciddi performans kaybına sebep olabilir.
SELECT country.name, city.name MAX(city,population) as max_pop
FROm country JOIN city on city.countrycode = country.code WHERE country.code IN ('USA','RUS','CHN') GROUP BY country.name, city.name ORDER BY max_op DESC LIMIT 3;



9 Mart 2021 Salı

Shuffle Algoritmaları

Giriş
Shuffle yani karıştırma işlemi de random sayı üretici kullanır. 

1. Fisher-Yates Algoritması
Fisher-Yates Algoritması yazısına taşıdım.

2. Daha Kötü Bir Shuffle Algoritması
Fisher-Yates algoritmasını bilmeyen insanlar safça şuna benzer bir kod yazıyorlar.
Random r = new Random();
for (int i = 0; i < a.size(); i++) {
    int index = r.nextInt(a.size());
    int temp = a.get(i);
    a.set(i, a.get(index));
    a.set(index, temp);
}
Bu kod sıradaki nesneyi, rastgele bir nesne ile yer değiştiriyor. Ancak zaten yer değiştirmiş bir nesnenin tekrar seçilme olasılığı yüksek. Bu yüzden Fisher-Yates algoritmasına göre daha yavaş çalışır. Fisher-Yates ise sondan başa doğru ilerler ve yer değiştiren bir nesneye tekrar dokunmaz.

3. Java İle Shuffle
Şöyle yaparız
// assume `cards` is a `List`, 
Collections.shuffle(cards); 
// cards is now shuffled
4. Belli Bir Aralıkta Karıştırılmış ve Tekrar Etmeyen Sayı Üretme
Belli bir aralıkta ve tekrar etmeyen sayı üretmek için önce sayılar bir listeye doldurulur daha sonra Collections.shuffle() çağırılarak rastgelelik sağlanır.

Örnek - Java
Şöyle yaparız
final List<Integer> l = new ArrayList<Integer>();
for (int j = 1; j < 7; j++ ) {
  l.add( j );
}
Collections.shuffle( l );