How I Designed Orchestrix: A Distributed E-Commerce System from Scratch
The architectural decisions, engineering trade-offs, and lessons behind building an event-driven commerce platform.
Orchestrix was never supposed to be an e-commerce platform. I originally wanted to build a Saga orchestration engine. My goal was to understand how independent services coordinate transactions, handle partial failures, and recover when something goes wrong.
E-commerce gave me a practical domain to explore those problems. But as I worked on the project, I wanted to build something beyond the orchestration engine. I wanted a complete experience where users could discover products, manage their carts, make wallet payments, and interact with customer support. That gradually introduced a different set of engineering challenges.
In my previous article, I explored how Orchestrix handles distributed transactions through Saga orchestration, compensation, and reliable event publication. This time, I want to take a step back and explain how I designed the system itself.
We'll build the architecture piece by piece, exploring why I chose certain technologies, what alternatives I considered, and the trade-offs behind each decision. Rather than starting with the complete architecture diagram, I want to show you how I arrived at it.
Why I Chose Microservices Over a Monolith
Before deciding on microservices, I considered whether Orchestrix actually needed a distributed architecture. A well-designed modular monolith can comfortably serve thousands of users, depending on their activity, infrastructure, and database access patterns. It simplifies deployment, debugging, and transaction management while still maintaining clear domain boundaries.
But I wanted to evaluate the architecture against the different workloads an e-commerce platform might encounter. Consider a hypothetical scenario with 10,000 concurrently active users:
Each user makes a catalog request every five seconds, generating approximately 2,000 read requests per second. During a promotional sale, 6,000 checkout attempts arrive within a minute, generating an average of 100 checkout requests per second.
What's interesting here is how differently each component experiences that traffic. The catalog primarily handles reads that can benefit from caching. Inventory deals with concurrent updates, potentially against the same product. Payment processing requires reliable transactions, while notifications can be processed asynchronously.
Scaling the entire application because one of these components experiences increased demand might be unnecessary. With microservices, I could horizontally scale the catalog service independently of the payment or inventory services. Each service could have its own resource allocation, deployment lifecycle, and data access strategy.
Independent data ownership also allowed me to design around the consistency requirements of each domain rather than applying the same approach everywhere. However, this flexibility comes at a cost. Operations that could previously execute within a single database transaction now require coordination across services. Network failures, message delivery, data synchronization, and observability become additional engineering responsibilities.
The workload assumptions alone don't prove that a monolith would be insufficient. They helped frame the architectural trade-offs I wanted to explore. I chose microservices for Orchestrix because I wanted independent scaling, explicit data ownership, and greater control over how different components handle failures.
The next decision was how these independently deployed services should communicate without introducing unnecessary coupling across the checkout workflow.
Why I Chose an Event-Driven Architecture
Once I had separated the services, I needed to decide how they would communicate. The simplest approach would have been synchronous communication using REST or gRPC. The Order Service could call the Inventory Service, wait for a successful reservation, and then call the Payment Service.
But consider what happens when payment processing becomes slow or temporarily unavailable. The order request remains dependent on the payment response. As more checkout requests arrive, waiting connections and resource consumption can increase, potentially affecting other parts of the system.
I wanted to separate order acceptance from order completion. Once an order was durably recorded, the remaining workflow could progress asynchronously without keeping the original HTTP request open. That led me toward event-driven communication.
However, choosing asynchronous messaging introduced another decision: which messaging system should I use? I considered three alternatives:
- RabbitMQ: A strong option for task distribution, message acknowledgments, and flexible routing.
- Redis Streams: A relatively lightweight option supporting persistent streams, consumer groups, and replay while entries are retained.
- Kafka: A partitioned event log supporting configurable retention, independent consumer groups, and offset-based replay.
All three could support a Saga-based workflow. My decision wasn't based on which one could simply deliver messages. I wanted commerce events to remain available beyond their initial consumption. An order-related event could be useful to the Saga Orchestrator, Notification Service, order projections, and potentially a future analytics pipeline.
With Kafka's retained-log model, these consumers could maintain independent offsets and process relevant events at their own pace. For Orchestrix, I used Redpanda as the Kafka-compatible event broker, as discussed in my previous article.
Of course, asynchronous communication introduces its own challenges. Consumer lag, duplicate delivery, event ordering, schema evolution, and eventual consistency all become part of the architecture. A message broker can absorb temporary differences between producer and consumer throughput, but it cannot eliminate a sustained processing bottleneck.
I chose a hybrid communication model: synchronous APIs for user-facing interactions that need immediate responses, and asynchronous messaging for distributed checkout coordination and downstream event processing. This allowed me to use each communication model where its trade-offs made sense, rather than forcing every interaction through the event bus.
Designing the Data Layer: Data Ownership and Polyglot Persistence
Separating the application into microservices introduced another important decision: should all services share a database, or should each service own its data?
A shared PostgreSQL database simplifies relationships between tables, SQL joins, and transactions involving multiple entities. However, it can also become a single point of failure (SPOF) without high-availability mechanisms. As the application grows, competing workloads and resource contention can turn it into a common performance bottleneck.
For Orchestrix, I chose the database-per-service pattern, allowing each service to manage and scale its data independently. The trade-off is that conventional SQL joins and foreign key constraints cannot directly enforce relationships across independent databases. Instead, services must rely on well-defined identifiers, API contracts, and event payloads to associate related business entities.
Retrieving information across domains may require API composition or event-driven read models, introducing additional complexity, data duplication, and eventual consistency.
Why PostgreSQL?
For the core transactional services, I chose PostgreSQL because of their consistency requirements. Inventory shouldn't become negative, wallet balances must remain correct under concurrent updates, and orders and their corresponding outbox records must be persisted atomically. PostgreSQL provides ACID transactions, relational constraints, row-level locking, and transaction isolation mechanisms that help enforce these invariants.
For example, I designed a wallet concurrency test where eight threads attempt to deduct $100 from a wallet containing $500. The expected outcome is exactly five successful deductions, three rejected transactions, and a final balance of zero. This is the kind of business invariant that motivated my use of pessimistic locking in the Payment Service.
Why Different Storage Engines?
Not every service has the same data access patterns. Rather than forcing every workload into PostgreSQL, I adopted a polyglot persistence approach. Each technology serves a specific purpose, although maintaining multiple storage engines introduces additional operational complexity.
Where Valkey Fits Into the Architecture
I chose Valkey, a Redis-compatible in-memory data store, for workloads that benefit from low-latency access. However, faster access doesn't always justify introducing another data store.
Payment deduplication is a good example. Rather than maintaining processed command identifiers in Valkey, the Payment Service persists them in PostgreSQL. Using Valkey could reduce lookup latency, but it would introduce another dependency and require coordination between two independent data stores. For financial operations, I prioritized durable state and transactional correctness over individual lookup performance.
Why I Considered Database Replicas
As part of the deployment architecture, I considered PostgreSQL primaries with read replicas to distribute read traffic. However, asynchronous replication introduces replication lag, meaning a read immediately following a successful write might return outdated information.
Consistency-sensitive operations, such as wallet deductions and inventory reservations, would continue relying on the authoritative primary. Read replicas improve read scalability, but they don't eliminate write contention or automatically guarantee high availability. Replication, failover, and backups need to be considered separately.
The underlying principle was to select storage technologies and consistency mechanisms according to each domain's requirements, rather than applying the same solution across the entire system.
Designing the Complete Commerce Workflow
Not every operation in Orchestrix requires the same communication model. Product discovery, viewing product details, and cart management are interactive operations where customers expect immediate responses. Synchronous APIs are a natural fit for these workloads.
Checkout, however, follows a different lifecycle. Accepting an order doesn't mean inventory has been reserved or payment has succeeded. Intermediate order states allow the frontend to communicate this distinction while the transaction progresses asynchronously.
Separating Transactional Writes From Reads
An order-history page may require information from several services, including product details, payment status, and order state. Fetching this information through multiple synchronous API calls introduces additional latency and service dependencies.
One approach I considered was maintaining a dedicated, event-driven order projection. This follows the principle of Command Query Responsibility Segregation (CQRS), allowing read models to be optimized independently of transactional write operations. The trade-off is eventual consistency. A delayed projection consumer could temporarily display an outdated order status.
Supporting operations, such as notifications, can also execute independently. A failed email delivery shouldn't reverse a successful purchase. The objective was to keep the critical checkout path focused on transactional correctness without making it dependent on supporting functionality.
Coordinating Distributed Transactions and Publishing Events Reliably
With independent services and asynchronous communication in place, I needed a mechanism to coordinate distributed business transactions. I chose Saga orchestration over choreography because centralized coordination provides better visibility into transaction states, failure recovery, and compensating actions. The trade-off is that the orchestrator becomes a critical component whose availability and state persistence require careful consideration.
Rather than adopting an existing workflow engine such as Temporal, I implemented a dedicated orchestration layer to explore these mechanisms directly. I covered the implementation in detail in my previous article.
Why I Considered Debezium and CDC
To address the dual-write problem between PostgreSQL and Kafka, I adopted the Transactional Outbox Pattern. For publishing outbox events, I considered two approaches:
- Polling: Simpler to implement and operate, but introduces periodic database queries and publication delays.
- Change Data Capture (CDC): Debezium captures committed changes from PostgreSQL's Write-Ahead Log (WAL), reducing the need for polling but introducing connector management, replication slots, and WAL retention concerns.
Although Debezium is part of my broader system design, the current implementation uses a polling-based publisher. At the current workload, polling was sufficient. I would introduce CDC when event volume, publication latency, or database overhead justified the additional operational complexity.
Both approaches require idempotent consumers to handle potential duplicate deliveries.
Designing for Failure, Recovery, and Observability
In an asynchronous system, an order might remain pending because a consumer is unavailable, a message couldn't be processed, or a downstream operation failed. I needed to distinguish temporary infrastructure failures from business failures. A database connection timeout might justify a retry, while insufficient wallet balance requires a different recovery strategy.
When Automated Recovery Isn't Enough
I incorporated dead-letter queues (DLQs) into the architecture to isolate messages that couldn't be processed after retry attempts. However, a DLQ only isolates the failure. It doesn't resolve it.
This motivated the inclusion of a governance layer, designed to give administrators visibility into failed transa
Comments
No comments yet. Start the discussion.