Leveraging Circuit Breakers, the Saga Pattern, CQRS, and API Gateways

By The Coding Gopher

Published: 2026-07-02

URL: https://thecodinggopher.substack.com/p/5-advanced-system-design-concepts


How to orchestrate distributed systems, maintain data integrity across boundaries, and prevent catastrophic cascading failures.

Once you have mastered the basics of horizontal scaling, load balancing, and database replication, the architectural challenges shift. You are no longer trying to figure out how to handle more traffic; you are trying to figure out how to manage the inherent chaos of dozens, or hundreds, of independent servers trying to talk to each other over an unreliable network.Scalability Patterns for Modern Distributed SystemsHorizontal scaling (or "scaling out") is the process of adding more machines or nodes to your existing infrastructure to distribute workloads, rather than upgrading the capacity of a single machine. It provides massive scalability and high fault tolerance, allowing seamless traffic handling without hardware limits.

When a monolithic application is split into microservices, the complexity moves from the code to the network. Here are 5 advanced concepts required to keep distributed architectures from collapsing under their own weight.

Subscribe now

1. The Circuit Breaker Pattern (Preventing Cascading Failures)

In a distributed system, slow is worse than dead.Must-Know Failure Modes in Distributed SystemsA cascading failure is a domino-effect event in an interconnected system where the failure of one part overloads or disrupts other components. This triggers progressive, compounding failures through positive feedback, often causing total system collapse.

If Service A (Frontend) calls Service B (Inventory), and Service B goes completely offline, Service A instantly gets an error and can show the user a fallback screen. But if Service B is just extremely slow (perhaps struggling with a deadlocked database), Service A’s network request will hang waiting for a response. If 1,000 users hit Service A, 1,000 threads will hang waiting for Service B, completely exhausting Service A’s memory. Soon, Service A crashes. Then Service C, which relies on A, crashes. This is a cascading failure.Circuit Breaker Pattern in Microservices - GeeksforGeeksThe circuit breaker pattern is a software design pattern used to detect and prevent cascading failures in distributed systems. It acts like an electrical fuse, temporarily halting calls to an unresponsive or failing service to allow the system to recover gracefully.

The Solution: The Circuit Breaker pattern sits between services. It monitors failure rates and timeouts. If Service B fails 10 times in a row, the circuit “trips” (opens). For the next 30 seconds, any request Service A makes to B is instantly rejected by the circuit breaker without actually sending the network request. This prevents Service A from exhausting its threads and gives Service B time to recover without being hammered by retries.

2. Distributed Transactions (The Saga Pattern)AlgoDaily - Transactions in SQLA database transaction is a single unit of work containing one or more database operations (like read, write, update, or delete). It follows an "all-or-nothing" approach, ensuring that either all operations succeed completely or none take effect, preserving data integrity even during system failures.

In a traditional monolithic database, if a user buys an item, you deduct their funds and decrement the inventory in a single ACID transaction. If either step fails, the database automatically rolls everything back.

In a microservice architecture, “Payments” and “Inventory” are separate services with completely separate databases. You cannot run a standard SQL transaction across them.Saga Pattern Demystified: Orchestration vs ChoreographyThe Saga pattern is a design pattern used to maintain data consistency in distributed systems, such as microservices, where traditional ACID transactions across different databases are not possible. Instead of locking resources, it breaks a distributed transaction into a sequence of smaller local transactions.

The Solution: The Saga Pattern breaks the transaction into a sequence of local transactions.

-

The Order Service creates a Pending order.

-

The Payment Service charges the card.

-

The Inventory Service reserves the item.

If the Inventory Service fails (e.g., the item is out of stock), the system must execute Compensating Transactions in reverse. The system automatically fires an event to the Payment Service to issue a refund, and an event to the Order Service to mark the order as Failed. It replaces strict database locking with eventual, application-level consistency.

𝐋𝐞𝐚𝐫𝐧 𝐭𝐨 𝐛𝐮𝐢𝐥𝐝 𝐆𝐢𝐭, 𝐃𝐨𝐜𝐤𝐞𝐫, 𝐑𝐞𝐝𝐢𝐬, 𝐇𝐓𝐓𝐏 𝐬𝐞𝐫𝐯𝐞𝐫𝐬, 𝐚𝐧𝐝 𝐜𝐨𝐦𝐩𝐢𝐥𝐞𝐫𝐬, 𝐟𝐫𝐨𝐦 𝐬𝐜𝐫𝐚𝐭𝐜𝐡. Get 40% OFF CodeCrafters: https://app.codecrafters.io/join?via=the-coding-gopher

This Substack is reader-supported. To receive new posts and support my work, consider becoming a free or paid subscriber.

3. Event Sourcing & CQRS

Traditional databases store the current state of an entity. If a user’s bank balance is $50, the database simply says $50.Event Sourcing Pattern in Microservices Architectures | by Mehmet Ozkaya |  Design Microservices Architecture with Patterns & Principles | MediumEvent sourcing is an architectural pattern where all changes to an application's state are stored as an immutable, sequential sequence of events. Instead of overwriting data in a traditional database, every action is appended to a log of events, which becomes the sole source of truth.

Event Sourcing abandons this. Instead of storing the current state, it stores an immutable log of every single event that ever happened (e.g., AccountCreated, Deposited $100, Withdrew $50). To find the current balance, the system replays the events from the beginning. This provides a perfect, undeletable audit trail, which is mandatory for financial and trading systems.CQRS - Command Query Responsibility Segregation Design Pattern -  GeeksforGeeksCommand Query Responsibility Segregation (CQRS) is a software architectural pattern that strictly separates the operations for reading data from the operations for writing data. Coined by Greg Young, it scales the programming concept of Command Query Separation (CQS) to the application and system architecture level.

Because replaying thousands of events for a simple read query is slow, this is almost always paired with CQRS (Command Query Responsibility Segregation). The architecture is split: the “Write” side appends events to the event log, while an asynchronous background process listens to those events and updates a separate, highly optimized “Read” database that simply holds the pre-calculated $50 balance.

4. Consensus Algorithms and The Split-Brain Problem

When you replicate a database across three servers, they must agree on who is the “Leader” (the server allowed to accept writes).Understanding the Split-Brain Problem in Distributed Systems -The split-brain problem in distributed systems occurs when a network partition disconnects a cluster into two or more independent, isolated groups. Because they can no longer communicate, both groups assume they are the sole authoritative system, leading to conflicting data updates and system corruption.

If a network cable is cut, isolating Server 1 from Servers 2 and 3, Server 1 might assume the others died and declare itself the Leader. Servers 2 and 3 assume Server 1 died, and elect Server 2 as the new Leader. You now have two independent Leaders happily accepting conflicting writes. When the network cable is fixed, the database is permanently corrupted. This is the Split-Brain Problem.Understanding Raft Consensus Algorithm: How it Works and Why it Matters |  by Mehar Chand | MediumThe Raft consensus algorithm works by electing a single, central leader node that takes complete responsibility for managing and replicating a system's log across a cluster of computers. Designed by researchers at Stanford University as a more understandable alternative to Paxos, Raft ensures that a cluster of machines can agree on a shared sequence of data changes even if some nodes crash or messages are lost.

The Solution: Distributed systems use Consensus Algorithms (like Raft or Paxos). These algorithms enforce a strict mathematical rule: a server can only become a Leader if it receives a vote from a majority (quorum) of the total nodes. In a 3-node cluster, you need 2 votes. Server 1 is isolated and only has 1 vote, so it demotes itself to a read-only state. Servers 2 and 3 have quorum, elect a Leader, and safely continue processing data.

Consensus algorithms are protocols used in distributed systems to ensure multiple independent nodes agree on a shared state or value, even when network partitions or node failures occur. Paxos and Raft are the two most prominent algorithms used to maintain data consistency across distributed systems.

5. Service Discovery & The API Gateway

When an infrastructure scales to hundreds of microservices, servers are constantly spinning up and shutting down based on load. Hardcoding the IP address of the “Payment Service” into the “Order Service” is impossible because that IP address might change every 10 minutes.Service Discovery 101: The Phonebook for Distributed SystemsService discovery is the automated process of tracking network services and their changing IP addresses or ports within a distributed system. It eliminates the need for hardcoded, static configurations, allowing microservices to locate and communicate with each other dynamically.

Service Discovery acts as a dynamic internal phonebook (e.g., HashiCorp Consul or Kubernetes CoreDNS). When a new Payment server boots up, it registers its IP with the discovery service. When the Order service needs to talk to Payments, it asks the discovery service for the current, valid IP addresses.API Gateway - ByteByteGo NewsletterAn API Gateway is a centralized server that acts as a reverse proxy, sitting between client applications and backend microservices. It intercepts incoming requests and routes, transforms, and secures them, functioning as a single, unified entry point for your entire system.

To prevent external clients (like mobile apps) from having to navigate this internal chaos, engineers place an API Gateway at the edge of the network. The Gateway is the single public entry point. It handles authentication, SSL termination, and rate limiting, and then dynamically routes the incoming HTTP request to the correct internal microservice.

This Substack is reader-supported. To receive new posts and support my work, consider becoming a free or paid subscriber.

Thanks for reading! This post is public so feel free to share it.

Share