Reflection on Designing Distributed System

Just finished reading “Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services” by Brendan Burns. I enjoyed reading the book. I think this book is going to add value to people who has recently get their hands on docker and orchestration tools like kubernetes. It is going to empower those developers/devops/admins by helping them to learn more about containerization design patterns. This book is only 150+ pages and it discusses wide range of tools and techniques with hands on example but I would definitely recommend this book for the theory and discussion rather than the practical aspect of it.

Containers establish boundaries that helps to provide separation of concerns around specific resources. When the scaling is not requirement and application runs on a single node, but the application is being run only on a single node, containerising still is going to be better choice because not only it helps us to scale but also it can be used to organise and maintain better.

Sometime in an application, we have tasks that runs in the background and other tasks that are served to endusers. Often the tasks that serves endusers are more important. We can prioritise those tasks in our containers by scaling those containers in a node appropriately.

When engineering teams starts to scale, for better engineering performance, usually a team of developers comprises of six to eight people. When more engineers join, usually it increases the number of teams. A better engineering performance, maintainability, accountability and ownership structure can be implemented by assigning the responsibility of a containerised application to a team. Additionally, often some of the components, if factored properly, are reusable modules that can be used by many teams. 

Single node patterns:

  • Sidecar Pattern: Sidecar containers, are a group of containers that runs together and stayed together on the same node, and they share processes, ports and so on. It can be a very useful when dealing with legacy services or 3rd party maintained closed source application about which we have very little knowledge. In sidecar pattern, unencrypted traffic is only sent via the local loopback adapter inside the container group, that makes the data and communication between them safe.
  • Ambassador Pattern: In ambassador pattern the two containers are tightly linked in a symbiotic pairing that is scheduled to a single machine. Ambassador can be used as proxy server. In a sharded system, ambassador pattern can be used to route to a Shard. Ambassador can be used for Service Broker as well.
  • Adapters: Although every application is different, they still have some things in common. They need to be logged, monitored, maintained, etc. Adapter patter takes advantage of this use case and implemented in a sidecar pattern. This common use case can be modularized and use as sidecar container. Popular use case can be accessing and collecting desired logs, monitoring performance by periodic executing a command, etc via a container that runs as sidecar.

Serving Patterns:

Replicated Load-Balanced Services: In replicated load balanced services, the same data is being replicated across multiple server and a service is being used as a load balancer.

Sharded Services: When the size of data becomes huge for a single machine, the data is splitted and distributed across multiple machine. A router is placed in front of the service to identify which shard to route to to fetch that data. Usually a carefully chosen hashing key is used to identify where the data is located and which server to route to. For better performance and reliability, replication and sharding is used together.

Scatter/Gather: Scatter/gather is quite useful when there is a large amount of mostly independent processing that is needed to handle a particular request. Scatter/gather can be seen as sharding the computation necessary to service the request, rather than sharding the data.

When there is more data that a single machine can hold or process in time, it becomes necessary to introduce sharding by splitting the data across multiple devices. Then when it comes to querying, it is going to require query to all the root notes then the partial responses from the nodes returns to the root node and that root node merges all of the responses together to form a comprehensive response for the user. The limitation of this approach is, the response time is dependent on lowest performing node, thus increased parallelism doesn’t always speed things up because of overhead or straggler on each node. Also mathematically speaking, 99th percentile latency on 5 node for individual requests becomes a 95th percentile latency for our complete scatter/gather system. And it only gets worse from there: if we scatter out to 100 leaves, then we are more or less guaranteeing that our overall latency for all requests will be 2 seconds. 

A single replica means that if it fails, all scatter/gather requests will fail for the duration that the shard is unavailable because all requests are required to be processed by all leaf nodes in the scatter/gather pattern. This risk is being addressed by adding multiple replica of a node.

Functions and Event-Driven Processing 

Function level decoupling: In microservice approach we splitted our application in small parts and managed by a team. FaaS takes it to the next level. It forces to strongly decouple each function of service.

 There is a common saying that 80% of the daily users are going to be using 20% of the features. For the rest of 80% features that are not being used extensively, can be an ideal candidate for FaaS that charges based on number of requests so we are only paying for the time when your service is actively serving requested and we are always paying for processor cycles that is largely sitting around waiting for a user request. 

The function in FaaS, dynamically spuns up in response to a user request while the user is waiting, the need to load a lot of detail may significantly impact the latency that the user perceives while interacting with your service and this loading cost can be amortized across a large number of requests. 

This approach also has many limitations, the function communicates with each other via network and each function instance cannot have high local memory. So maybe it is a good fit for responding to temporal events, but it is still not sufficient infrastructure for generic background processing and the requiring states needs to be stored in a storage service which adds more complexity in code.

Because of this highly decoupled nature, from the other functions, there is no real representation of the dependencies or interactions between different functions, it becomes difficult to find bugs. Also the cost of a bug related to infinity loop is high.

Batch Computational Patterns: for reliable, long-running server applications. This section describes patterns for batch processing. In contrast to long- running applications, batch processes are expected to only run for a short period of time. 

Work Queue Systems: In the containerised work queue, there are two interfaces: the source container interface, which provides a stream of work items that need processing, and the worker container interface, which knows how to actually process a work item. The work processor can be implemented by a container that processes Shared Work Queue where items in the queue as batch operation or it can be implemented in multi-worker pattern which transforms a collection of different worker containers into a single unified container that implements the worker interface, yet delegates the actual work to a collection of different, reusable containers.

Depending on workload, shared work queued containers needs to be scaled accordingly. Keeping one or few workers running when the frequency of works coming is very low can be overkill. Depending on the workload for a task we can also consider implementing multi-worker pattern using kubernetes jobs to implement work processor. We can easily write a dynamic job creator, which is going to spawn a new job when there is a new item in the queue.

Event-Driven Batch Processing: Work queues are great for enabling individual transformations of one input to one output. However, there are a number of batch applications where you want to perform more than a single action, or you may need to generate multiple different outputs from a single data input. In these cases, you start to link work queues together so that the output of one work queue becomes the input to one or more other work queues, and so on. This forms a series of processing steps that respond to events, with the events being the completion of the preceding step in the work queue that came before it.

In an complex event driven system, often the event needs to go through many steps where data needs to divided into few queues, sometime it requires to merged to get an output.

Copier: The job of a copier is to take a single stream of work items and duplicate it out into two or more identical streams. 

Filter: The role of a filter is to reduce a stream of work items to a smaller stream of work items by filtering out work items that don’t meet particular criteria. 

Splitter: divide them into two separate work queues without dropping any of them. 

Sharder: divide up a single queue into an evenly divided collection of work items based upon some sort of shard‐ ing function

Merger: the job of a merger is to take two different work queues and turn them into a single work queue. 

Coordinated Batch processing:

To achieve more complex event driven architecture, we are going to need more coordinated batch processing techniques.

Join (or Barrier Synchronization) : In merge, it does not ensure that a complete dataset is present prior to the beginning of processing but when it comes to join, it does not complete until all of the work items that are processed. It reduces the parallelism that is possible in the batch workflow, and thus increases the overall latency of running the workflow. 

Reduce : Rather than waiting until all data has been processed, it optimistically merge together all of the parallel data items into a single comprehensive representation of the full set. In order to produce a complete output, this process is repeated untill all of the data is processed, but the ability to begin early means that the batch com‐ putation executes more quickly overall.

How to run a simple load test on Geth Node

In this blog, I am going to share a simple code snippet that I have used to run a load tests on geth node. To get things done, I am using the locust python library, and to connect to get node, I am using web3 library. This piece of code finds 10 addresses at the initialization step. After initialization, it spawns a predefined number of users and tries to find the balance of 1 of those 10 addresses.

Continue reading “How to run a simple load test on Geth Node”

A dirty patch to fix Django annotate related group by year/month/day related bug

Recently I was working on a Django project with a team, where we wanted to run some group-by queries for analytical data representation. As we already know that Django does not directly support group-by but there are ways one can achieve it by using Django values and annotate functions.


It was supposed to return a QuerySet that contains a count of entries that has been created in a specific year. Instead, it was returning a QuerySet that containing individual data.

During the first step of my investigation, I tried to log the SQL query that is associated with this query and it logged something like this.

SELECT EXTRACT(YEAR FROM `tablename`.`timestamp`) AS `year`, COUNT(`tablename`.`id`) AS `ycount` FROM `tablename` GROUP BY EXTRACT(YEAR FROM `tablename`.`timestamp`), `tablename`.`timestamp`

The SQL query that I wanted my ORM to create was:

SELECT EXTRACT(YEAR FROM `tablename`.`timestamp`) AS `year`, COUNT(`tablename`.`id`) AS `ycount` FROM `tablename` GROUP BY EXTRACT(YEAR FROM `tablename`.`timestamp`)

The difference was subtle, but the Django was grouping by using two fields and that was the reason behind this unintended result.

How can we possibly bypass this possible bug from Django? Since we had no way to group timestamps. The solution I had in mind is, while running queries, what if I can temporarily replace the value of timestamp on the runtime? Since values, or F does not allow to replace value of a field I had to rely on extra function that comes with Django.

             .values('year')extra(select = {'timestamp': 'year'})

Which has produced the following SQL:

SELECT DATE(`tablename`.`timestamp`) AS `date`, MAX(`tablename`.`quantity`) AS `count` FROM `tablename` GROUP BY DATE(`tablename`.`timestamp`), (date)

It is probably not the ideal solution but it got things done before the Django team solves the problem. If you have a better solution in mind, I would love to talk about it and implement it.

Writing a k8s controller in GoLang: delete pods on secret change

The motivation behind writing was to explore how customer controller works in kubernetes. As I was doing it, i felt like doing something that solves a problem. Most of the deployment practically we use has some form of secret mounted with it. It is usually a common practice to iterate those secret every now and then, but one problem that we face is that, after we change the secrets of kubernetes, it does not reflect the pods immediately. It is never a flaw but the idea here is, along with the new deployment of the application, the secrets are going to be changed but for people like me, who wants to see the changes immediately, it can be annoying sometime. One way to solve the problem is to kill the pods associated with the deployment one by one. As the pods are being recreated, it picks the latest secret instead of the old one. Usually developers uses kubectl command to delete the pods but in this blog I am going to write a custom controller using go lang.

Continue reading “Writing a k8s controller in GoLang: delete pods on secret change”

Shallow diving k8s components: etcd

Etcd is a high available key-value data storage that stores all the data necessary for running a Kubernetes cluster. The first time I learned about etcd i asked myself why? There are so many production-ready key-value databases out there. Why did the Kubernetes team choose etcd? What am I missing? That lead me to learn more about etcds. Etcd is perfect for kubernetes because of at least 2 reasons. One of them is because it is robust in nature. It makes sure that the data are consistent across the cluster. It makes sure that it is highly available. Another reason is, it has a feature called watch. Watch allows an observer to subscribe to changes on a particular data. It goes perfectly with Kubernete’s design paradigm.

Continue reading “Shallow diving k8s components: etcd”

Linux namespaces and how docker internally uses those namespaces

While using docker it is quite natural to feel like we are dealing with a virtual machine because we can install something in a container, it has an IP, file tree is different and whatnot. In reality, containers are just a mechanism that allows Linux processes to run with some degree of isolation and separation. Containers basically use few different primitives in Linux combined. By using Linux namespaces containers can make these happen.


What are namespaces? Namespaces are another Linux kernel primitive that can be used to control access and visibility of resources. Generally, when properties like names or permissions change, it is visible only within the namespace and it is not visible to the processes outside of it. So it makes it look like that the process has its own isolated copy of a given resource. Docker uses these properties of the namespace to provide isolation. Namespaces can map resources outside a namespace to a resource inside a namespace. Linux has at least 7 kinds of namespaces that cover different kinds of resources: Mount, UTS, IPC, PID, Network, User, Cgroup. Sometimes we these namespaces individually and sometimes we have to use them together because types like IPC, Cgroup, PID use file systems that need to be mounted. A name server does not stay open when there is no running process on it or a bind mount. That’s why a docker gets killed when the process inside it gets killed, it is because of how Linux System deals with its PID 1, which I am going to discuss later in this blog.

How would I find out the namespace of a process? We can find any information about a process by accessing the proc virtual file system. If we check carefully we should be able to find a directory called ns which contains symbolic links to the namespace. These symbolic link structures can provide us the information about the namespace type and inode number that the kernel uses. By comparing this inode number we can confirm if both of the processes are part of the same namespace or not.

readlink /proc/$$/ns/uts

How can we use namespace? A set of Linux syscall is used to work with namespaces, most commonly clone, unshare, etc. Clone is a sort of more general version of the fork system call that allows us to create a new child process.  It is controlled by a set of flags that we can if we want the new child process to be in some new namespaces and we want to move the process to move itself from one namespace that it is currently resident in, to another existing namespace. unshare supports the same flags as clone. unshare is a syscall that a running process can use to move into a new namespace. Namespaces automatically close when nothing is holding them open so it ceases to exist when the running process stops or kills. Creating a user namespace requires no privilege but for another namespace, it requires privilege. So time to time you will be needed to use sudo. We can use commands like setns, nsenter, and ip netns to switch or enter from one namespace to another namespace.

Every docker container has its own hostname. Docker uses UTS namespace to achieve it. UTS namespaces isolate two system identifiers of node name (generally known as hostname) and the NIS domain name. On a  Linux system, there might be multiple UTS namespaces. If one of those processes changes the hostname the change will be visible to the other processes within that namespace.

Lets use unshare command to create new namespaces and execute some command in those namespaces.

echo $$

readlink /proc/$$/ns/uts

sudo unsure -u bash

echo $$

readlink /proc/$$/ns/uts

hostname new_host_name

readlink /proc/$$/ns/mnt

nsenter -t PID -u bash

Another fascinating feature of a Linux container is that it is successful to make us believe that every container has a completely different set of files but in reality, it uses Linux mount namespaces to provide a separate view of the container image mounted on the containers root file system. Mount namespace allows us to isolate a set of mount points seen by a process. Mount points are just tuples that keep track of the device, its pathname, and the paren of the mount. By tracking parents, mount point helps us to maintain a single directory hierarchy. So across namespaces, we can have processes that have a different set of mount points and they see a completely different single directory hierarchy tree. It hides the host file system from view to share data across containers or between the host and a container.  Volumes are really amount added to the container’s mount namespace.  There are ways to share subtrees that allow us to propagate mount points across different namespaces.

Docker makes sure that from one container we don’t access another process of a container. PID namespaces play a great role in it. PID namespace isolates process id. We can only see the id of a process when the process that is part of the same PID namespaces. Since every PID in a namespace is isolated and unique in that isolated space, we don’t need to worry about potential conflicts of id. We can use the PID namespace in many ways, if we want to freeze a process and move it to another core or another machine, we can do that without thinking about the conflict it may cause in terms of PID conflict. PID namespace also allows us to use PID 1 across different namespaces. PID 1 is a special thing on any UNIX system. PID 1 is the parent of all orphaned processes and is responsible for doing certain system initialization. PID namespace is different from all other namespaces. PID namespace maintains a hierarchy. This type of hierarchy has a depth of 32. Each PID namespace has a parent PID namespace that has been initiated by clone() or unshare().  For when the fork happens the process stays at the same level but when clone happens it goes to a lower level. All these 32 generations are initiated from PID 1 on that process. So as a parent of all processes, PID 1 can see all the processes in the namespace, but lower-level PIDs can’t see higher-level PIDs. When PID 1 goes down or gets killed Linux kernel panics and gets restarted. When PID 1 in a namespace goes away, the namespace is considered unusable

sudo unshare -p -f bash
echo $$ 
ls /proc/

We are going to see many processes, but we should not see any processes, because PID should not have any processes yet, right? It is because we unshare only the PID namespace, and totally forgot to unshare mount point, so we can still have access to all processes that are part of PID1 across all namespaces.

Now let’s unshare mount and PID namespace together:

sudo unshare  -m -p -f bash

mount -t proc none /proc

docker typically uses a separate network namespace per container. Network namespace a separated view of the network with different network resources like routing table rules, firewall rules the socket port, some directories in /proc/net and sys/class/net, and so on. Network namespaces can be connected using a virtual ethernet device pair or veth pair and these vets pair are being isolated using network namespace. These veth pair are connected to a Linux bridge to enable outbound connectivity. Kubernetes pods and ECS tasks get a unified view of the network and a single IP address exposed to address all of the containers in the same pod or task. Every container has its own socket port number space. It can use some NAT rules on the container we could run a web server on port 80.

ip link

sudo unshare —net ip link

touch /var/run/netns/new

mount —bind /proc/$$/ns/net /var/run/netns/new


docker run —name busybox  —detach busybox

ps ax | grep busybox

sudo redlink /proc/PID/ns/net

docker inspect busybox | jq .[0].NetworkSettings.IPAddress

nsenter --target PID --net ifconfig eth0

ip link | grep veth

ifconfig vethxxxxxx


Since dockers are just a clever use of Linux namespaces, we can interchangeably use all namespace-related commands and tools to debug dockers as well. For example, to enter namespaces we can use commands like setns, nsenter, ip netns. To demonstrate that we can run a docker image, and find the process id of that image, and then let’s use nsenter command to access to enter the namespace and run commands inside that namespace that has been created by docker.

docker run —name redis  —detach redis
ps ax | grep redis
nsenter —target PID —mount /usr/local/bin/redis-server


How docker internally handles resource limit using linux control groups

While using docker it is quite natural to feel like we are dealing with a virtual machine because we can install something in a container, it has an IP, we can ssh it, we can allocate memory and CPU to it like any virtual machine but in reality, containers are just a mechanism that allows Linux processes to run with some degree of isolation and separation. Containers basically use few different primitives in Linux combined. If containers are just based on Linux primitives how are we being able to set limits to memories and CPUs? The answer is very simple and it is already available in the Linux system, docker takes leverage of Linux Control groups.

What are Control groups? Control groups are commonly known as cgroups. Cgroups are the abstract frameworks in Linux systems for tracking, grouping, and organizing Linux processes. No matter what process it is, every process in a Linux system is tracked by one or more cgroups. Typically cgroups are used to associate processes with a resource. We can leverage cgroups to track how much a particular group of processes is using for a specific type of resource. Cgroup plays a big role when we are dealing with multitenancy because it enables us to limit or prioritize specific resources for a group of processes. It is particularly necessary because we don’t want one of our resources to consume all the CPU or say io bandwidth. We can also lock a process to run a particular CPU core using cgroup as well.

We can interact with the abstract framework of cgroups through subsystems. In fact, the subsystems are the concrete implementations that are bound to resources. Some of the Linux Subsystems are Memory, CPU time, PIDs, Devices, Networks. Each and every subsystem are independent of each other. They have the capability to organize their own processes separately. One process can be part of two independent cgroups. All of the c group subsystems organize their processes in a structured hierarchy. Controllers are responsible for distributing specific types of resources along the hierarchy Each subsystem has an independent hierarchy. Every task or process ID running on the host is represented in exactly one of the c groups within a given subsystem hierarchy. These independent hierarchies allow doing advanced process-specific resource segmentation. For example when two processes share the total amount of memory that they consume but we can provide one process more CPU time than the other.

This hierarchy is maintained in the directory and file structure. by default, it is mounted in /sys/fs/cgroup the directory but it can be mounted in another directory of choice as well. We can also mount multiple cgroup locations in multiple locations as well, which comes in handy when a single instance is using by multiple tenants and we want one tenant cgroup to be mounted on his disk area. Mounting cgroup can be done using the command:

mount -t cgroup2 none $MOUNT_POINT

Now lets explore the virtual filesystem of cgroup:

ls /sys/fs/cgroup
ls /sys/fs/cgroup/devices

Some of the resource controllers apply settings from the parent level to the child level, an example of such controller would be the devices controller. Others consider each level in the hierarchy independently, for example, the memory controller can be configured this way. In each directory, you’ll see a file called tasks. This file holds all of the process IDs for the processes assigned to that particular cgroup.

cat /sys/fs/cgroup/devices/tasks

It shows you all of the processes that are in this particular cgroup inside this particular subsystem but suppose that you have an arbitrary process and you want to find out which c groups it’s assigned to you can do that with the proc virtual file system. Let’s look at that the proc file system contains a directory that corresponds to each process id.

ls /proc

To see our current process we can use the command:

 echo $$
cat /proc/<pid>/cgroups

Let’s say I want to monitor a group for how much memory it is using. We can read the virtual file system and see what it returns.

cat /sys/fs/cgroup/memory/memory.usage_in_bytes

What are seeing these files and directories everywhere? It just interfaces into the kernel’s data structures for cgroups. Each directory has a distinct structure. Even if you create a new directory, it will automatically create a bunch of files to match up. Let’s create a cgroup. To create a cgroup, we just need to create a directory, at least this is how the kernel keeps track of it.

sudo mkdir /sys/fs/cgroup/pids/new_cgroup
ls /sys/fs/cgroup/pids/new_cgroup
cat /sys/fs/cgroup/pids/new_cgroup/tasks

The kernel keeps track of these processes using this directory and files. So adding or removing processes or changing any settings is nothing but changing the content of the files.

cat /sys/fs/cgroup/pids/new_cgroup/tasks
echo $$ | sudo tee /sys/fs/cgroup/pids/new_cgroup/tasks

You have written one line to the task files, haven’t you? Now let’s see what it is inside the tasks file:

cat /sys/fs/cgroup/pids/new_cgroup/tasks


We are supposed to see at least 2 files because when a new process is started it begins in the same cgroups as its parent process. When we try to use command cat, our shell starts another process and it appears in the tasks file.


We can limit the number of processes that a cgroup is allowed to run by modifying pids.max file.

Echo 2 | sudo tee /sys/fs/cgroup/pids/new_cgroup/pids.max

Now let’s try to run 3 processes instead of two and it is going to crash our shell.


Now that we have a basic understanding of cgroups. Let’s investigate cgroups inside our docker containers.

Let’s try to run a docker container with a CPU limit of 512 and explore the cgroups.

docker run —name test —cpu-shares 512 -d —rm buxybox sleep 1000

docker exec demo ls /sys/fs/cgroup/cpu

docker exec demo ls /sys/fs/cgroup/cpu/cpu.shares


So basically docker is using my commands to manipulate the group setting files to get things done. Interesting indeed. If it is not a virtual machine, these files are supposed to be on our machine too, isn’t it? yes, you got it right. Usually, these files are located somewhere in /sys/fs/cgroup/cpu/docker. Usually, there is a directory with a 256 hash that contains the full docker id.

ls /sys/fs/cgroup/cpu/docker
cat /sys/fs/cgroup/cpu/docker/<256big>/cpu.shares

Cgroup mechanism is tied to namespaces. If we have a particular namespace defined then we can add the namespace to the cgroup and everything that is a member of the cgoup becomes controlled by the cgroup.

Just want to give a word of warning before modifying anything of a cgroup we should keep in mind that dependencies there might be on the existing hierarchy. For example, amazon ECS or google c advisor uses the secret hierarchy to know where to read CPU and memory utilization information.

Reflection on “Designing Event Driven Systems for microservices using kafka”

Previously in my blog I have talked about microservices, and in a microservice architecture service teams think of their software as being a cog in a far larger machine. So suddenly for service team your customers or business people are not the only consumer of your application but are other applications that is consuming their application and they really cared that your service was reliable and application started to become platforms and as we discussed previously microservices does not share a single database with multiple application, but most of the time for service to perform it needs to access the data in a decoupled way as the key concept to implement microservices is, strong cohesion and low coupling. One of the pattern that was suggestion was event driven design pattern. Thank you confluent for offering me this free book on event driven system, called “Designing Event-Driven Systems: Concepts and Patterns for Streaming
Services with Apache Kafka” by Ben Stopford.

The beauty of events is that it decouples which means no one orders other do things, which reduces the dependency in services. It also makes a new entity to get used to with the system without the need of modification in other service. Even there are few techniques that encourages to decouple application from the database where the database is growing huge. We can do event based approach when a service to service data sharing is needed.

To make event drived programming easier Kafka has many useful features. Kafka has Connect interface, which pulls and pushes data to wide range of interfaces and datastores. Streaming APIs can manipulate data on the fly, that makes kafka encourages request-response protocols like Enterprise Service Bus. But kafka is much higher level tool compared to ESB. ESBs focus on the integration of legacy and off-the-shelf systems, and kafka is using an ephemeral and comparably low-throughput messaging layer. Kafka cluster has a distributed system at core, that provides high availability, storage, and linear scale-out. Using Kafka, we can store and lets users define queries and execute them over the data held in the log and we can pipe into views that users can query directly. It also supports transactions, just like a database but it is said that Kafka is a database inside out, a tool for storing data, processing it in real time, and creating views. Like most streaming systems implement the same broad pattern where a set of streams is prepared, and then work is performed one event at a time. Join, Filter, Process, in Kafka Streams or KSQL it can be implemented as well.

Where does kafka sits from the architectural level? One single Kafka cluster can be placed at the center of an organization, as the architecture of kafka inherits and inspired from storage systems like HDFS, HBase, or Cassandra compared to the traditional messaging systems that implement JMS (Java Message Service) or AMQP (Advanced Message Queuing Protocol) and that makes it more scalable. The underlying abstraction of kafka is, partitioned log sequentially being appended in a distributed computer system across multiple computers with redundancy which is designed to handles case like high-throughput streaming, mission-critical scenarios, ordering needs to be preserved. Its ability to store datasets removes the queue-depth problems that plagued traditional messaging systems. Kafka messaging system sits a partitioned, replayable log. this replayable log–based approach has two primary benefits. First it makes it easy to react to events that are happening now, with a toolset specifically designed for manipulating them. Second, it provides a central repository that can push whole datasets to wherever they may be needed. When a service wants to read messages from Kafka, it “seeks” to the position of the last message it read, then scans sequentially, reading messages in order while periodically recording its new position in the log. Taking a log-structured approach has an interesting side effect. Both reads and writes are sequential operations. This makes them sympathetic to the underlying media, leveraging prefetch, the various layers of caching, and naturally batching operations together. This in turn makes them efficient. In fact, when you read messages from Kafka, the server doesn’t even import them into the JVM (Java virtual machine). Data is copied directly from the disk buffer to the network buffer (zero copy)—an opportunity afforded by the simplicity of both the contract and the underlying data structure.

To ensure high availability kafka keeps redundant copies of same logs across multiple machines (usually/ideally 3) as replica that makes kafka failure tolerant. When a machine goes down we are not losing any data, and when that machine status changes to up, it sync up with other nodes and start contributing to cluster, that makes kafka not only reliable but also scalable. With Kafka, hitting a scalability wall is virtually impossible in the context of business systems. Even though kafka keep multiple copies of same data across machines but if we need to ensure paranoid level security to ensure the persistence of our highly sensitive data, we may require that data be flushed to disk synchronously with an overhead of throughput. If we absolutely have to rely on this approach it is recommended to increase the producer batch size to increase the effectiveness of each disk flush on the machine. When keys are not provided the replications are usually spread data across the available partitions in a round-robin fashion but when a key is provided with the message, it uses a hash of the key to determine the partition number. Kafka ensures that messages with the same key are always sent to the same partition which ensures strong orders. Sometime key-based ordering isn’t enough to maintain global ordering, use a single partition topic. When we are reading and writing to a topic we are basically reading and writing to all of them. By default messages are retained for some configurable amount of time for a topic. Kafka also has special topics called compacted topics, it stores data with respect to a consistent foreign key. It work like a simple log-structure merge-trees (LSM trees). It scans through a topic for old messages that has been  superseded (based on their key) and removes them in a periodic fashion. So if you find two logs with same key, don’t open a bug report right away. Although it’s not uncommon for kafka to see retention based or compacted topics holding more than 100 TB of data yet not no confuse it with a database. Multitanancy is very common when we are dealing with multiple services but it opens up the potential for inadvertent denial-of-service attacks which causes degradation or instability of services. To solve this problem Kafka introduces a throughput control quotas, that enables us to define an amount of bandwidth that would be allocated to specific services which ensures that it operates in the boundary of  enforced service-level agreements or SLA. Client authentication is provided through either Kerberos or Transport Layer Security (TLS) client certificates, ensuring that the Kafka cluster knows who is making each request.

Now lets go back to event driven programming. As we are used to batch operations and sequential programming, if a database is connected with our software, we are used to with the architecture where we ask question and we wait for an answer but in our world where data is being populated like rabbit and maybe our database size is huge. Maybe we should not waste our time waiting for answer, maybe we should ask then then keep doing something else that needed to be done and when our database is done producing the result that we have asked for, it should tell us by issuing and event that the task is done. Now a days the application that are using event-driven architectures, Event Sourcing, and CQRS (Command Query Responsibility Segregation) is helping them as a break away from the pains of scaling database centric systems. Maybe our database size is not huge, maybe database centric approach is working wonderfully. But it works for individual applications but we live in a world of interconnected systems. We need a mechanism for sharing data from one application to other that complements this complex, interconnected world. We can constantly push data from one application into our applications using events. To be event driven an applications needs to react, complex application may need to blend multiple streams together to make something meaningful out of it, it may need to build views and changing state and move itself forward.

One of such pattern for service to service communication could be, The Event Collaboration Pattern. The Event Collaboration Pattern allows a set of services to collaborate around a single business workflow, with each service doing its bit by listening to events, then creating new ones. For example basket service publishes an event to OrderRequested topic when an order is placed. Order service is subscribed to OrderRequested topic and when it listens to that event it validates the order and when it is done validating it creates an event to  OrderValidated. Payment service is interested about order validations so it is already subscribed OrderValidated events and when it a new event is published at OrderValidated it try to process payment and publish it to OrderPaymentProcessed topic. Order service is interested about OrderPaymentProcessed events so it when a new event gets published it confirms the order by publishing events at OrderConfirmed topic. Shipping service is interested about this topic and it has lots of status, and every status change can be a new topic that would interest the Order service and finally when Order is delivered Shipping service publish its event to OrderDelivered event. Order service is subscribed to this topic and it changes status of the event to delivered. As we can see, every service is decoupled and every service is collaborating with the services by publishing events (rather than making synchronous REST calls). If a service is not scaling properly it is just going to add more unprocessed messages to its events but it won’t crush the system or make the whole system down. That is the beauty of this pattern. One thing to note here is that the more events that we create the system is getting slower, to make the system faster, we need to appreciate parallel execution otherwise we won’t be able to make our system fast enough.

Let’s talk about Shared database approach. As kafka logs can makes data available centrally as a shared source of truth but with the simplest possible contract. This keeps applications loosely coupled. Query functionality is not shared; it is private to each service, allowing teams to move quickly by retaining control of the datasets they use. For example suppose in our previous example OrderDelivered event both order and email service are interested about this event and email service is producing email based on the event but the order service is lagging behind to update the order, in that scenario the user might get an email with a link that has not been created yet or the views are not updated yet and that would make the system inconsistent which is a violation of CAP theorem. In situation like this Kafka queries can come handy. For a certain event we can query for associated other event and see if that has been fulfilled or not then a service can do what it was supposed to do, but as we have mentioned previously in this blog, maybe paranoid style of data storage is necessary in this approach.

Database has a number of core components which includes a commit log, a query engine, indexes, and caching. Instead of conflating these components inside a single black-box which is known as database, separating them using stream processing tools. These parts can exist in different places, joined together by the log. Kafka Streams can create indexes or views, and these views behave like a continuously updated cache, living inside or close to your application. So in this approach rather than letting our application ask for data, we are basically pushing data to the application and let it process the task it needs to do.

Speaking of commands and queries. Commands are actions that can expect something to happen. Events are both a fact and a notification that has no expectation of any future action. Queries are a request to look something up, that does not expect any action but it a result of some data. From the perspective of a service, events lead to less coupling than commands and queries. Command Sourcing is essentially a variant of Event Sourcing but applied to events that come into a service, rather than via the events it creates. If we are using a database with our service and it is being updated from recalculation and processing the events there are few other benefits associated with it. If they are stored, immutably, in the order they were created in, the resulting event log provides a comprehensive audit of exactly what the system did. Another amazing thing about event driven programming is that, if at certain point we lost few of our services due to our bug, those services does not lose all its data that needs to be processed by the system because the events are stored in kafka and using kafka we can store data persistently as long as it has been predefined. If we implement CQRS using kafka, imagine how powerful it is going to get, as kafka keeps all its logs in its persistent storage, heavens forbid for some reason if our database gets into some sort of trouble we are not missing any data whatsoever. After the point of rollback of a backup, we have to populate the rest of the data from kafka log. So that is pretty neat.

In-Process Views with Tables and State Stores is an Event Sourcing and CQRS technique which can be implemented using Kafka’s Streams API as it lets us implement a view natively, right inside the Kafka Streams API without needing external database! From the example above when the “OrderValidated” event returns to the orders service, the database is updated with the final state of the order, before the call returns to the user. One of the most reliable and efficient way to achieve this can be using a technique called change data capture (CDC). Most databases write every modification operation to a write-ahead log so that at if the database encounters an error, it can recover its state from there. Many also provide some mechanism for capturing modification operations that were committed. Connectors that implement CDC repurpose these, translating database operations into events that are exposed in a messaging system like Kafka. Because CDC makes use of a native “eventing” interface, which is very efficient, as the connector is monitoring a file or being triggered directly when changes occur, rather than issuing queries through the database’s main API, and also it is very accurate, as issuing queries through the database’s main API will often create an opportunity for operations to be missed if several arrive, for the same row, within a polling period. ome popular databases with CDC support in Kafka Connect are MySQL, Postgres, MongoDB, and Cassandra. There are also proprietary CDC connectors for Oracle, IBM, SQL Server, and more.

Speaking of collisions and merging, collisions occur if two services update the same entity at the same time. If we
design the system to execute serially, this won’t happen, but if we allow concurrent execution it can. There is a formal technique for merging data in this way that has guaranteed integrity; it is called a conflict-free replicated data type, or CRDT. A useful way to generalize these ideas is to isolate consistency concerns into owning services using the single writer principle. When locks are used widely  in concurrent environments, and the subsequent efficiencies that we can often gain by consolidating writes to a single thread. The idea closely relates to the Actor model. From a services perspective, it also marries with the idea that services should have a single responsibility. responsibility for propagating events of a specific type is assigned to a single service—a single writer. This single writer approach can be implemented in kafka by modifying enforcing permission of topic at kafka. In single writer principle we are basically accepting eventual consistency over a global consistency.

Kafka data transactions do remove duplicates, allow groups of messages, state stores backed by a Kafka topic. When a http calls fail (maybe due to timeout), it is very common to give it a retry but maybe our retry is generating multiple database entry. It goes tricky when it happens on a system where the payment is involved. It makes system idempotent. Transactions in Kafka allow the creation of long chains of services, where the processing of each step in the chain is wrapped in exactly-once guarantees. Kafka can do that because they are not being operating using TCP, they are operating over UDP (User Datagram Protocol) which gives them a higher level of abstraction, which handles delivery, ordering, and so on. As Kafka is a broker, there are actually two opportunities for duplication. Sending a message to Kafka might fail before an acknowledgment is sent back to the client, with a subsequent retry potentially resulting in a duplicate message. On the other side, the process reading from Kafka might fail before offsets are committed, meaning that the same message might be read a second time when the process restarts. In kafka transactions it use commit as a marker message introduces in Snapshot Marker Model. After the messages are send it sends commit signal and until commit signals are sent it is not being available for read. Commit markers are coordinator. The overhead of this commit markers can be reduced by using it wisely. For context, For a batches that commit every 100 ms, with a 1 KB message size, have a 3% overhead when compared to in-order, at-least-once delivery.

Kafka consumer and producer needs to agree on the data format and schema.  For schema management: Protobuf and JSON Schema are both popular, but most projects in the Kafka space use Avro. For central schema management and verification, Confluent has an open source Schema Registry that provides a central repository for Avro schemas. New schema updates need to be backward compatible. Sometime it is absolutely necessary to change schema, which will break backward compatibility. For cases like this creating a new topic is recommended and also we would need to push data to both topic.

There are actually two types of table in Kafka Streams: KTables and Global KTables. With just one instance of a service running, these behave equivalently. However, if we scaled our service out—so it had four instances running in paral lel—we’d see slightly different behaviors. This is because Global KTables are broadcast: each service instance gets a complete copy of the entire table. Regular KTables are partitioned: the dataset is spread over all service instances. Whether a table is broadcast or partitioned affects the way it can perform joins. With a Global KTable, because the whole table exists on every node, we can join to any attribute we wish, much like a foreign key join in a database. This is not true in a KTable. Because it is partitioned, it can be joined only by its primary key, just like you have to use the primary key when you join two streams. So to join a KTable or stream by an attribute that is not its primary key, we must perform a repartition.

Ensuring consistency in data at the time of scaling can also be challenges as data propagation across nodes takes time, to solve this we can partition topic based on product id this way, product with same product id will always go to same node, which will make this operation consistent always. Inventory product and order products are maybe spread across multiple nodes and to be able to join them we need to reshuffle everything, this process is called Rekey to Join. data arranged in this way is termed co-partitioned. Once rekeyed, the join condition can be performed without any additional network access required. But then again in our next operation we may need to join few other tables, so we need to use rekeyed to join them, so our previous rekeys get shuffled in this way, so it can become a less practical solution depending on our situation.

Reflecton on Building Microservices Designing Fine Grained Systems

Recently I have been reading “Building Microservices Designing Fine Grained Systems” by Sam Newman. Indeed it is a must read book if you are trying to move toward microservices. This book is going to influence and reflect a lot at my work, so I was thinking I should definitely write a reflection blog. This is what I am attempting to do here. Obviously my point of view will differ in terms of many things, I will be explaining my take aways from the book and I will be trying to reflect my point of view and experience as well. Sam Newman is not a fanboy like me, so he expressed his caution while using docker, but I am a fanboy of docker/kubernetes so obviously I would have whole different perspective how docker makes managing orchestrating microservices easier or where and how docker/kubernetes fits in. Maybe I am going to write about it in another blog.

I agree with Sam Newman when he compared our software industry with fashion industry. We are easily dominated by tech trends. We tend to follow what other big organization is doing. But it has its reasons as well. This big organizations who are setting trends, they are doing a lot of experiments, and publishing their findings and some time publishing few open source tools along with it, as a biproduct of their work and smaller organization like us, most of the time we don’t get the luxury to experiment in that large scale, we don’t have the luxury to innovate, but we can easily become the consumer of those tools and we can easily take leverage of the knowledge that has been shared with us. So we take the easy route.

One of the key thing about microservices is that, every service needs to have some form of autonomy, it can depend on other service for data or information that is not within the boundary or context,  but it has to have its own data source that it owns, where it can store and retrieve data that is within the boundary or the context of the service. It can take leverage the best programming language that matches with its goal, it can use the database that matches with its need. Independence of tooling is a great feature, it reduces the tech debts in a very positive way. That’s probably the main selling point of microservices.

At a service oriented architecture, maybe it can be a common practice to directly access database that other service is primarily using, the reason is very simple I need a data that the other service has, so I am accessing the data that I need. But what happens when the owner of the service change its schema for representing their data better? The other service that is consuming the data of that service locks up, the other services which were consuming the data won’t be able to consume the data that it absolutely needs. So maybe, we need less coupling in our services then what we are already got used when we were using service oriented architecture. The best way that we can think of, maybe we can do that using REST APIs, when we would need a data from other service we would request the data using API calls to the service who owns the data and we don’t know the internal details about how the data is being stored. We need the data not its internal representation. Less coupling allows us to change the internal representation of the things without impacting the expected result that it needs to produce. The import term here is, it allows us to improve and change without going through huge hassles and long meetings with stakeholders who runs other services that will be affected for the change in your internal representation. Not only database, usually the system that has been designed to make RPC calls to change or to collect resources of other services are also prone to this problem.

When it is microservice we are talking about, it is easy to imagine that there is a huge code base with millions of lines of code that does pretty much everything on its own, it is struggling with load and the codebase is getting out of hand and almost unmanageable and we don’t want that so we want to move out of it. We want to split this huge monolith into few manageable services with manageable loads. Now dividing a monolith is not always an easy task. Setting a boundary is often harder but every service needs to have a well defined boundary. When dividing monolith we can follow a simple rule of thumb that says code that changes together will stay together which is known as high cohesion and the codes that does not change together may split apart. Then we can further split it based on domain, functionality, special technical needs. For example maybe a facebook like friends network can leverage a graph structured database, maybe neo4j or graphql in that case it deserves to be separated as a different service that use the appropriate technical tools that it needs.

Service to service communication in microservice is tricky, many people are using trusted network based security where the idea is, we try out best (invests more) to secure our parameter/border, it is hard to get into the parameter but once you are inside the parameter we trust you with everything. For organization like this few extra header that defines username is enough. But there are some other organization they are not being able to guarantee with 100% accuracy that their parameters are secured, there are so many hacking techniques as well that allow them to breach the boundary pretending to be someone else. So maybe we need to maintain some form of security and privacy even when we are communicating inside our secured parameter, from one service to another service. All internal communication can be encrypted using some form of HTTPS which encrypts the message and verify that the message source and destinations are accurate. Some organizations are relying on JWT as it is very light weight but still every service needs to have the capability to verify that token. A shared token has to be shared between the services and it has to be done using secured fashion.

When deciding between orchestration and choreography, choreography should be the best pattern because otherwise if we try to orchestrate by one service, we are basically overpowering it compared to other services that eventually it will start becoming a god service that will keep dominating other services all the time. We don’t want service to service domination. We want equal distribution of load and responsibility and almost equal importance. Also it has its problems as well, because in a microservice world new services start to appear everyday and old services gets discarded everyday it becomes real hassle for the owner of the god service to track them and to add and remove those service calls to our god service. Rather than a service who is making rest api calls to notify other services to do certain things, we can fire events and any other service who might be interested on that event will subscribe to that event and play its part when the event is triggered. If new service comes in, it is easier for it as well to subscribe to that event. It can be implemented using kafka or maybe Amazon SQS.

In microservice world it is extremely important to isolate the bug, the bug from one service tends to cripple other services. So it often becomes difficult to identify the real bug in appropriate service. So we need to have proper testing mechanism that that will isolate a service while testing and at the time of testing other api calls that it makes to other services needed to be mocked so it needs to have proper setup for isolated testing. So we would servers that is capable to imitate the ideal behavior of other service. When testing, it would be wise to have another environment that has its own set of database, in that way we would be able to test how resource creation is responding on a particular service. We talked about isolated testing, but integration testings are also important. As in micro services, there are so many moving pieces, maybe a service is calling an api that has been removed or the url has changed for some reason, (maybe the owner of the service has forgot to inform other stakeholdsrs) in that case the service that is calling the api, it won’t be able to perform what it was supposed to do. So integration tests are important, it is going to test when integrated together it is still performing the way it should be performing.

Every service needs to get monitored and there has to be a set of action that would take place when a service is down. For example maybe there can be a sudden bug introduced in one service causing huge CPU or memory can make the service go offline. It can affect the other service that is running on that machine. It is usually recommended that one service is being hosted on one machine so that the failure on one service does not cascade the problem to another service. There also should a well placed rule or circuit breaker on when are we going to consider a service is down and when are we going to stop sending traffic to a service. Suppose one of are service is down, in that case another thing to note here is that is it going to be wise to show the whole system is down when there is only one service that is down out of maybe 100s of services. Instead of doing that we can replace a portion of website with something else. For example when the ordering service of an ecommerce is down. It won’t be wise to shut the whole website down, we can let user visit the site and rather than letting them click “place order” button we can show them “call our customer care to place order”. So if implemented wisely micro service can reduce our embarrassment. Netflix has implemented an opensource smart router called zulus that can open and close a feature to group of users while the rest of the users get that is default. It can come handy time to time as well. There are many tools out there to monitor servers, from opensource world we can use nagios, or we can use 3rd party monitoring tools like datadog, new relic, cloudwatch and the options are many.

When talking about monitoring, we also need to be conscious that sometime our app is going to pass all the health checks yet it will produce a lot of error. For such situations maybe we need to monitor the logs, maybe a centralized log aggregation and monitoring system (famous ELK stack) can be helpful. As we are dealing with microservice, I am sure we have so many servers and it won’t be wise to poke in every server to collect logs when there is crisis, a log aggregation platform is a necessity, that’s how I want to put it. Our log aggregation system needs to be intelligent to fire an alarm when it reaches a certain number of error messages. Depending on the severity of error message, maybe it is time to let the circuit breaker know that we don’t want any traffic on that service until it has been sorted out.

In microservices we are dealing with 100s and 1000s of services, so there will always be some sort of deployment going on, either it is on this service or that service. If DevOps culture is being adopted small changes will be incouraged to go on production. The philosophy is if a bug is introduced due to small change, it will be easier to spot and easier to fix compared to a huge chunk of code. As each services are interconnected, if a service go down even for a second other services gets affected so zero downtime is a must. We can use blue green deployment or cannery deployment strategy to achieve zero downtime thingy and it is absolutely important. If something goes wrong in a deployment there has to have a well defined strategy to rollback to previous build. It is better if it has a CI/CD pipeline attached with it. Chef, Puppet like server automation tools comes handy because it helps us to automate the monotonous tasks. When automation scripts are being written, it is being tested over and over again, it is faster and more reliable, same goes for rollback.

Micorservices makes security much easier, as we know from CIA triangle, we can’t have everything. Often when we want to ensure security, we will need to slow our systems down as  a trade off. Now, as we are splitting our services, does all our services needs equal amount of security be ensured (read, does all our services needs get slow?). Often some services need more security than other. So microservices will give us opportunity to use the write security where security is needed, so it won’t slow the whole server down, when a specific service needs special security measure.

Sometime DNS management gets troublesome. It takes hours to get everything propagated across the servers. It can When we are dealing with interconnected services (and there are 100s of them) it will be really troublesome if server to server DNS records are not being reflected the same way, so we can have our own service discovery mechanism, we can have our own DNS server. We can take advantage of Zookeeper, Consul, Eureka and so on.

Scaling microservices can be challenging some time. It is said that people use 20% of the feature 80% of the time, in other word 80% of the feature are never been used. So when we have a heavy load, linearly increasing all the servers most of the time will be a wrong choice. So we need to setup more complex scaling techniques that needs to be implemented on each service separately. Our load balancers are getting smarter everyday so it won’t be too hard to implement.

Newman has pointed out few interesting things about implementation of microservices, one of the key point he has mentioned is about Conway’s Law. If the organization is not organized, and works independently in terms of team to department and collaboratively with other department like a microservice, it would be challenging for that organization to adopt microservices. So it makes me wonder maybe for smaller startup, maybe microservices are not the solution they should look for. Also when it comes to the ownership of service, in smaller organization maybe the same person or team is going to own all of the services. It is going to be a huge overhead as well.