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 transactions and support controlled manual recovery when automated mechanisms aren't sufficient.
Such interventions require safeguards around idempotency, transaction state validation, and auditability to prevent recovery attempts from introducing further inconsistencies.
Making the system observable
I incorporated Prometheus, Grafana, and distributed tracing into the observability architecture.
Metrics such as request latency, error rates, and consumer lag help identify bottlenecks, while distributed tracing helps connect operations across service boundaries.
These mechanisms introduce additional operational complexity, but independent services are considerably harder to manage without visibility into their behavior.
Failure isolation is only valuable when failures can be detected, understood, and recovered from safely.
Designing for three different user roles
As Orchestrix evolved into a complete commerce platform, I wanted it to support three different types of users:
Customers: Discover products, manage carts, make wallet payments, track orders, and raise support tickets.
Administrators: Manage users, oversee platform operations, and monitor system activity.
Customer support agents (BPO): Manage support tickets, communicate with customers, and assist with order-related issues.
Supporting these roles introduced different authorization requirements. I implemented role-based access control (RBAC), with the API Gateway responsible for validating JWTs and applying route-level access policies before forwarding requests to downstream services.
Designing real-time customer support
Customer support introduced a different communication requirement. Unlike traditional request-response APIs, conversations between customers and support agents require bidirectional communication.
I used WebSockets with STOMP to support real-time messaging, PostgreSQL to persist conversations, and Valkey to track online agent presence.
Another interesting problem was ticket allocation.
Rather than assigning every incoming ticket to a random agent, I explored least-busy routing, where tickets are distributed based on agent availability and existing workload.
Concurrent ticket allocation also required careful handling. If two agents attempted to claim the same ticket simultaneously, the system needed to prevent duplicate assignments.
For the ticket-claim mechanism, I used PostgreSQL's FOR UPDATE SKIP LOCKED, allowing concurrent transactions to skip ticket rows already locked by another transaction and select the next available ticket.
This avoided introducing a separate distributed locking mechanism for an operation that could be coordinated within PostgreSQL itself.
Building these capabilities made Orchestrix more than a checkout workflow. It introduced operational requirements around authorization, real-time communication, workload distribution, and customer support.
Putting the complete architecture together
The individual architectural decisions now come together in the complete Orchestrix system design.
The diagram represents both the current implementation and proposed architectural enhancements, including Debezium-based CDC, PostgreSQL read replicas, and an expanded analytical data pipeline.
I haven't introduced Spark or a data warehouse because the current transaction volume doesn't justify the additional operational complexity. As the platform evolves, these components could support more advanced business analytics and machine learning workloads.
Beyond the conventional commerce architecture, I also wanted to explore how AI could improve product discovery and customer support without becoming a dependency of the critical transactional workflow.
That led to the design of a dedicated AI subsystem.
Extending Orchestrix with AI
I wanted to explore how AI could improve the commerce experience beyond a conventional product search or customer support interface.
Rather than embedding AI functionality directly into the existing services, I built a dedicated AI Service using Python and FastAPI. This allowed me to manage model dependencies, inference workloads, and deployment independently of the transactional services.
If an external LLM provider becomes unavailable, customers should still be able to browse products and complete purchases.
Agent orchestration with LangGraph and DSPy
Different user requests require different execution strategies.
A customer asking for a laptop suitable for software development needs product retrieval and recommendations. Someone asking about an existing order needs access to structured business data.
I used LangGraph to define the execution workflow and DSPy to implement intent-based routing.
A supervisor classifies the incoming request and routes it to one of two specialists:
Catalog Agent: Retrieves relevant product information and generates grounded responses.
Tool Agent: Selects predefined operations intended for order lookups, support assistance, and image-based product information extraction.
I kept the workflow relatively simple, with one routing decision followed by specialist execution, rather than introducing autonomous agent loops.
Designing the product retrieval pipeline
For product discovery, I implemented a multi-stage RAG pipeline using PostgreSQL with the pgvector extension.
Pure vector similarity search can return several nearly identical products. I wanted the retrieval pipeline to balance relevance, diversity, and contextual accuracy.
The pipeline works in three stages:
Dense vector retrieval: NVIDIA embeddings and pgvector cosine similarity retrieve the top 20 product candidates.
Maximal Marginal Relevance (MMR): Reduces those candidates to 10, balancing relevance with diversity.
Cross-encoder reranking: NVIDIA Nemotron reranks the candidates and selects the top three for answer generation.
This introduces additional inference latency, but it gives me greater control over the quality of the context supplied to the language model.
If the reranking provider becomes unavailable, the retrieval pipeline can fall back to vector-based results.
One limitation of relying exclusively on dense vector retrieval is that semantic similarity may not always capture exact product names, model numbers, or specific technical specifications.
To address this, I plan to extend the retrieval pipeline with hybrid search, combining BM25-based lexical retrieval with dense vector search. This would allow the system to benefit from both keyword precision and semantic understanding before applying diversity filtering and reranking.
Managing inference costs and observability
I introduced a LiteLLM-backed model factory to support multiple providers, including NVIDIA, Groq, and OpenRouter.
Valkey provides exact-match response caching for catalog queries, avoiding repeated model execution for equivalent normalized prompts. PostgreSQL telemetry and Langfuse instrumentation provide visibility into token consumption, model selection, routing decisions, and latency.
The current implementation uses exact-match response caching. A further optimization I plan to introduce is semantic caching, where semantically similar queries can reuse previously generated responses even when their wording differs.
However, this requires careful consideration of similarity thresholds, cache invalidation, and user context to avoid returning irrelevant or outdated responses.
The current implementation establishes the retrieval and routing architecture, while authenticated business-tool execution, event-driven catalog synchronization, and cache invalidation require further refinement.
What designing Orchestrix taught me
Building Orchestrix changed the way I approach system design.
When I started, my attention was primarily on architectural patterns, technology choices, and how different components communicated. But as the system evolved, I began spending more time thinking about what could go wrong, which guarantees each component needed to provide, and how one architectural decision influenced another.
I also experimented with concurrency testing, load testing, stress testing, and failure scenarios to explore how the system behaved beyond its expected execution paths.
Some architectural decisions simplified individual services while increasing the complexity of the overall system. Others introduced additional infrastructure in exchange for greater flexibility, reliability, or independent scaling.
There are still areas where I would improve the architecture, and some components in the system design represent future enhancements. I see that as a natural part of engineering. Architecture should evolve alongside the requirements, workloads, and evidence gathered from the system itself.
Perhaps the most valuable lesson from building Orchestrix was understanding that good system design requires more than knowing which technologies and patterns are available. It requires understanding why they belong in a particular system, what problems they introduce, and when their complexity becomes justified.
A good architecture is one whose decisions you can explain, whose trade-offs you understand, and whose behavior you can validate.
π Blog by Naresh B. A.
π¨βπ» Backend & AI Systems Engineer | Distributed Systems Β· Production ML
π Portfolio: [Naresh B A]
π« Let's connect on [LinkedIn] | GitHub: [Naresh B A]
Thanks for reading. This is my personal engineering perspective, and I'd genuinely be interested in hearing where you agree or disagree.β€οΈ






Top comments (0)