The OpenTel E-Commerce System
local graph
Chapter 3 — The OpenTel E-Commerce System
Section titled “Chapter 3 — The OpenTel E-Commerce System”In Chapter 1, we saw how a checkout failure can hide behind healthy-looking dashboards. This chapter introduces the concrete system where that failure plays out: OpenTel E-Commerce.
From Chapter 2, we also carry one key idea forward: Rust runtime and memory behavior shape real production symptoms. Under load, allocation pressure, lock contention, and async scheduling all influence latency and failure patterns across service boundaries.
Just as you cannot learn to be a detective in a town with zero crime, you cannot learn to diagnose problems in a system that never breaks. Simple “Hello World” applications lack the latency, concurrency conflicts, and partial failures found in production. To bridge this gap, this chapter introduces OpenTel E-Commerce, a purposefully complex microservices application.
We did not build this application to be easy; we built it to be real. It serves as our baseline for chaos, a sandbox that simulates how distributed services inevitably grow apart and fail independently. By operating a system where stock reservations time out, queries degrade under load, and errors cascade, we create the perfect laboratory for applying the OpenTelemetry concepts covered in this book.
This is an architecture baseline chapter, not a telemetry implementation chapter. Our goal here is a shared system context so that Chapters 4 onward can serve as an instrument for explaining this request journey end-to-end.
In this chapter, we will cover the following key topics:
- OpenTel E-Commerce: System Architecture (Understanding the microservices design)
- Domain Modeling (From database schema to Rust types)
- Service Boundaries and Responsibilities (Gateway, Products, Inventory, Orders)
- Navigating the Codebase (Repository structure and key files)
- Inter-Service Communication (The Saga Pattern for distributed transactions)
- The Backend Request Journey (Tracing a checkout request through all services)
- Current State: Logging Without Observability (Why println! isn’t enough)
- Why Observability is Non-Negotiable (The cost of not having visibility)
OpenTel E-Commerce: System Architecture
Section titled “OpenTel E-Commerce: System Architecture”OpenTel E-Commerce follows a standard microservices architecture, emphasizing realistic separation of concerns rather than simplicity.

figure 3.1
Figure 3.1 – The OpenTel E-Commerce architecture with Gateway, three backend services, and a schema-isolated PostgreSQL instance
The backend implementation utilizes Rust and the Axum web framework, structured around a central gateway and three core services. By relying on HTTP REST APIs for communication, the system replicates the isolation found in modern production environments. This architecture leverages Rust’s type safety for performance while retaining the complexities of distributed coordination, creating an system that is robust locally but challenging globally.
- OtelMart Service (Gateway): Acts as the entry point and implements the Backend-for-Frontend (BFF) pattern. Rather than exposing raw backend APIs to the client, the BFF aggregates, filters, and shapes data specifically for the frontend’s needs. It proxies the catalog and checkout traffic to the appropriate backend services via HTTP.
- Products Service: Manages the catalog, requiring support for complex search logic due to its read-heavy nature.
- Inventory Service: Serves as the source of truth for stock, handling high concurrency write operations (reservations) and ensuring strict consistency.
- Orders Service: Acts as the orchestrator, managing the checkout lifecycle and coordinating data across products, inventory, and payments.
All services utilize a single PostgreSQL instance but remain isolated through dedicated schemas - one each for products, inventory, orders, and users. We use a single database solely to reduce local Docker overhead; from the perspective of our Rust services and OpenTelemetry, the tracing complexity is identical to that of querying physically separate databases. Each service operates as an independent containerized process, communicating exclusively via HTTP REST APIs.
How do we keep services from reaching each other’s tables? Each service configures its database connection pool explicitly. For example, the Inventory service sets search_path TO inventory, so a query like SELECT * FROM product_inventory automatically resolves to the inventory.product_inventory table without needing a schema prefix. Every other service is configured the same way for its own schema.
This is a convention, not a security boundary; a service could still reference another schema using a fully-qualified name like orders.orders. In production, you would add PostgreSQL role-based permissions to enforce hard isolation. For our purposes, the convention is sufficient: it ensures that services naturally stay in their own lane, and if the Orders service needs product data, it must call the Products Service API over HTTP. This is exactly the inter-service communication pattern that makes distributed tracing essential.
Running Locally: We use Docker Compose to orchestrate all services. Each service runs in its own container with isolated database schemas (products, inventory, orders, users). Services communicate via an internal Docker network using container hostnames (http://orders:3003). When you run docker‑compose up ‑‑build, you’re not just starting containers, you’re summoning a distributed system with all its failure modes: network partitions, service startup ordering, partial failures, and schema isolation. See the repository’s README for detailed setup instructions.
Domain Modeling: From Database to Rust
Section titled “Domain Modeling: From Database to Rust”Now that we understand the service boundaries, let’s see how data flows through them. The first challenge: identity.
A well-designed domain model bridges the gap between your database schema and your application code. In OpenTel E-Commerce, we balance the strict correctness required in a financial system with the flexibility needed for a modern product catalog.
Identities and Types
Section titled “Identities and Types”One of the first challenges in a distributed system is identity. We employ a dual identifier strategy:
- Internal ID (
i32): Used strictly for database joins and foreign keys, ensuring fast and index-friendly operations. However, this numeric ID can be duplicated across different databases. - External ID (
UUID): Exposed to the frontend and other services, preventing enumeration attacks and allowing ID generation client-side or in upstream services without database roundtrips. Unlike numeric IDs, UUIDs are guaranteed to be unique across all services and databases.
In our Rust code, this duality is represented as follows:
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]pub struct Product { pub id: i32, pub uuid: Uuid, // ...}The id field is public so that SQLx’s FromRow derive macro can populate it from database rows. To prevent internal IDs from leaking into API responses, our response-facing structs (like ProductDetail) use #[serde(skip)] on the id field, keeping it invisible to clients while remaining accessible to the database layer. We use a plain i32 rather than a newtype like ProductId(i32) to keep the baseline simple. Since internal IDs never cross service boundaries (only UUIDs do), the risk of mixing up IDs across services is low in practice.
This UUID based approach is critical for distributed systems. When the Orders Service requests product details, it passes the product UUID to the Products Service. This ensures that the same business entity carries a consistent identifier across all services, even when they use completely different databases. This simplifies debugging by allowing you to filter logs and traces across all services for a single entity (e.g., “show me all traces involving this specific product”). However, it’s important to distinguish this from tracing a request. A single product UUID might appear in thousands of concurrent requests, whereas the Trace ID (introduced in the next chapter) assigns a unique identifier to a single operational flow, stitching the distributed journey together.
We also strictly avoid floating-point math for monetary values. While f64 is suitable for graphics, it can introduce unacceptable rounding errors in pricing. Instead, we use bigdecimal::BigDecimal (mapping to PostgreSQL’s DECIMAL) to ensure that 10.00. This also matters for observability: when you record revenue as a metric or attach a cart total as a trace attribute, you need the telemetry to match the database exactly, avoiding floating-point drift (e.g., $10.00000001) that can break financial dashboards.
Service Boundaries and Responsibilities
Section titled “Service Boundaries and Responsibilities”OtelMart Gateway (BFF)
Section titled “OtelMart Gateway (BFF)”As the single entry point for all client requests, the Gateway acts as a transparent reverse proxy to the Products, Inventory, and Orders services, shaping their responses for the Angular frontend. Throughout this book, the Gateway carries a single, deliberately simple workload: guest checkout. The customer’s email and shipping details arrive in the request body, and orders.is_guest_order defaults to true — there is no authenticated-user identity on the traced path. This keeps the early chapters focused on distributed-tracing mechanics rather than auth plumbing.
From an observability perspective, the Gateway is still the natural anchor for request identity. In , it becomes the trace entry point, where the root span is created, and request-scoped attributes (such as the customer email) are attached so every downstream service inherits that context automatically.
Products Service
Section titled “Products Service”The catalog is hierarchical, utilizing a materialized path pattern (e.g., path 1/23/45) for efficient retrieval of entire category subtrees in a single query. Products leverage PostgreSQL’s GIN (Generalized Inverted Index) indexes to support full-text search across names and descriptions. Unlike a standard B-tree index that maps one value to one row, a GIN index maps each individual word (or token) to every row that contains it, making it ideal for searching within text columns. This provides search-engine-like capabilities directly within the primary database.
Inventory Service
Section titled “Inventory Service”The Inventory service has one job: never oversell. Everything else is negotiable. The available_quantity is not merely a field we update; it is a generated column in PostgreSQL (stock_quantity ‑ reserved_quantity). A generated column is a database-computed field: PostgreSQL automatically recalculates available_quantity every time stock_quantity or reserved_quantity changes. This guarantees that our “available” stock is mathematically tied to our physical stock and reservations—a formula enforced by the database itself, not by application code. We can never drift out of sync due to a buggy update statement or forgotten code path.
Orders Service
Section titled “Orders Service”The Orders service represents the true complexity of a real-world transaction system. An “Order” is far more than a simple database row; it is a point-in-time snapshot of a binding agreement between the customer and the business.
The design decision here reveals a crucial principle that separates theoretical systems from production ones: denormalization for immutability. When an order is created, we do not simply store a product_id reference. Instead, we copy the product_name, sku, and unit_price directly into the order_items table. At first glance, this seems wasteful. Why duplicate data?
Consider what happens when a product’s price changes, an everyday occurrence in retail. A month later, a customer reviews their purchase history. If we had only stored the product_id, the system would reconstruct the price from the current product record. The customer sees they paid 29.99 at the time of purchase. When they contact support asking, “Why does the order say 19.99?”, you have created an unnecessary support case and eroded customer trust.
In production systems, this denormalized snapshot is non-negotiable for three critical reasons:
- Auditability & Incident Reconstruction: Every order is immutable proof of state at a specific point in time. When investigating a production incident tied to a specific checkout trace, having a denormalized snapshot means you don’t have to guess what the product data looked like “at the time.”
- Compliance: Jurisdictions worldwide require this for tax records, consumer protection regulations, and dispute resolution.
- Customer Service: When a customer disputes a charge, you must know exactly what they received and what they paid for; do not reconstruct it from tables that have since been modified.
From an observability standpoint, these design choices, stable UUIDs for correlation and denormalized snapshots for stable telemetry, transform chaotic, ever-changing databases into reliable sources of truth for your distributed traces. The cost of duplicating a few fields pales in comparison to the operational cost of trying to reconstruct the past state during a P1 outage or defending yourself against a regulatory inquiry.
Navigating the Codebase
Section titled “Navigating the Codebase”Before we dive into distributed transactions, let’s orient ourselves to the actual code. The repository is organized as a single Cargo workspace with four member crates:
opentel-ecommerce/├── otelmart/ # OtelMart Gateway (port 4200)├── products/ # Products Service (port 3001)├── inventory/ # Inventory Service (port 3002)├── orders/ # Orders Service (port 3003)├── schemas/│ └── init/ # SQL schema definitions per service├── Cargo.toml # Workspace root└── docker-compose.yml # Local orchestrationFigure 3.2 – The Cargo workspace layout of the OpenTel E-Commerce repository
Each service follows a consistent structure:
orders/├── src/│ ├── handlers/ # HTTP endpoint handlers (create_order, get_order)│ ├── models/ # Domain types (Order, OrderItem, OrderStatus)│ ├── db/ # Database queries and repository pattern│ └── main.rs # Service initialization, routing, middleware├── Cargo.toml # Dependencies (axum, sqlx, tokio, etc.)└── Dockerfile # Container image definitionFigure 3.3 – The internal directory structure of a service crate, with Orders shown as the representative example
Key files to explore:
orders/src/handlers/orders.rs- Thecreate_orderhandler that orchestrates the saga patterninventory/src/handlers/inventory.rs- Reserve and confirm stock operationsproducts/src/db/mod.rs- Product catalog queries with full-text searchschemas/init/- SQL schema definitions per service (products, inventory, orders, users)
When you read the code in later chapters, you’ll see how these handlers are instrumented with OpenTelemetry. For now, they’re just plain Rust functions making HTTP calls and database queries—exactly the kind of code that needs observability.
Inter-Service Communication: The Distributed Transaction
Section titled “Inter-Service Communication: The Distributed Transaction”These services don’t live in isolation. When a customer clicks “Buy,” three services must coordinate—and any one of them can fail. Here’s how we handle that complexity.
Microservices must communicate effectively to fulfill complex business workflows. In OpenTel E-Commerce, the most critical flow is order creation. This process is not a simple insert. It constitutes a distributed transaction that spans three services and multiple failure domains.
The “Happy Path”
Section titled “The “Happy Path””When a user clicks “Buy”, the Orders Service takes on the role of orchestrator:
- Validate: It queries the Products Service for details (price, name) to ensure the user is not purchasing a non-existent item.
- Reserve: It instructs the Inventory Service to hold the stock: “Reserve 1 unit of Item X”.
- Commit: Only after the stock is reserved does it insert the order into its own database.
- Confirm: Finally, it instructs Inventory to permanently deduct the stock.
The “Unhappy Path”
Section titled “The “Unhappy Path””In a monolithic architecture, this entire sequence would be encapsulated within a single database transaction (BEGIN...COMMIT). If any part of the process failed, the database would automatically roll back all changes.
In a distributed system, however, there is no global rollback.
If the Orders Service reserves stock but fails to save the order (due to a full database disk or a code bug), we end up with an orphaned stock reservation. The Inventory Service believes the item is sold, but no corresponding order exists.
To manage this, we implement a Saga Pattern. A Saga is a pattern for managing distributed transactions: instead of relying on a single database rollback, each service compensates for failures by calling a “compensating operation” on dependent services. When a step fails, we manually trigger rollback requests to undo previous steps. Here is the critical logic in us create_order handler:
// 1. Reserve stockmatch reserve_stock(&state, item.product_uuid, item.quantity).await { Ok(_) => { reserved_items.push((item.product_uuid, item.quantity)); } Err(response) => { // If reservation fails, we must manually undo any PRIOR reservations. // This is best-effort: if the release call itself fails, we log and move on. // A background reconciliation job would catch leaked reservations in production. release_all_reserved_stock(&state,&reserved_items).await; return response; // already an HTTP response (impl IntoResponse), not a Result }}
// ...
// 2. Try to save order to DBif let Err(e) = tx.commit().await { // CRITICAL: The DB commit failed, but we already told Inventory to reserve! // We must manually call the Inventory API to undo the reservation. release_all_reserved_stock(&state,&reserved_items).await; return ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({ "error": "Failed to commit transaction", "details": e.to_string() })), ) .into_response();}Snippet simplified for readability. See code/base/orders/src/handlers/orders.rs in the repository for the full handler, which also performs product validation, payment insertion, and confirm_all_sales after a successful commit.
Notice that release_all_reserved_stock is called without checking its return value. This is intentional: it’s a best-effort compensation. The function internally logs any errors, but there’s no meaningful recovery if the rollback itself fails. This release_all_reserved_stock function makes network calls to the Inventory Service. But what if those network calls fail?
If the network is down when we try to release stock, the system enters an inconsistent state. We have “leaked” inventory, items are marked as reserved in the Inventory Service, but no corresponding order exists in the Orders Service. From the customer’s perspective, the checkout failed, so they try again. But the inventory system still sees the first reservation, potentially double booking the item. This is a classic distributed system problem, and it’s exactly the kind of silent failure that creates support nightmares customer complaints about “phantom reservations,” inventory mismatches, and lost sales. Without observability, you have no way to detect or diagnose these leaks.
This is precisely where distributed tracing becomes invaluable for managing Saga patterns. Ideally, the entire create_order process is captured as a single parent trace. Each step in the saga—reserving stock, committing to the database, and crucially, the compensating actions like release_all_reserved_stock —would appear as a distinct child span within that trace. When a transaction fails, the resulting trace doesn’t just show an error; it visually documents the entire failure-recovery process. You can see exactly which compensation steps were attempted, how long they took, and whether the rollback itself succeeded or encountered a network error, turning a complex distributed failure into a clear, chronological story.
The Backend Request Journey
Section titled “The Backend Request Journey”To understand what we’ll instrument in the following chapters, let’s trace a single checkout request from HTTP entry to database commit. This is the canonical request flow that we’ll use throughout the book to demonstrate observability patterns.
The Canonical Checkout Request (HTTP Entry to Database)
Section titled “The Canonical Checkout Request (HTTP Entry to Database)”When a user clicks “Buy Now” on the frontend, here’s the complete journey:
- HTTP Entry - > OtelMart Gateway (Port 4200)
- Step:
POST /api/orders- Action: Receives checkout request with product UUIDs, quantities, shipping address, and payment details
- Responsibility: Request routing (guest checkout — no session validation on this path)
- Step:
- Gateway - > Orders Service (Port 3003)
- Step:
POSThttp://orders:3003/orders (proxied)- Action: Forwards checkout request to Orders orchestrator
- Note: Trace
- Step:
- Orders - > Products Service (Port 3001)
- Step:
GET http://products:3001/products/{uuid}- Action: Fetch product details (price, name, availability)
- Database: Product service queries
products.productstable - Why: Orders need the current price and product metadata
- Step:
- Orders - > Inventory Service (Port 3002)
- Step:
POSThttp://inventory:3002/inventory/reserve- Action: Reserve stock for the order
- Database: Inventory service updates
inventory.product_inventorytable - Why: Prevent overselling (saga pattern step 1)
- Step:
- Orders - > Own Database
- Step:
INSERT INTO orders.orders- Action: Persist order to orders database
- Database:
orders.ordersandorders.order_itemstables - Why: Create an immutable order record
- Step:
- Orders - > Inventory Service (Port 3002)
- Step:
POSThttp://inventory:3002/inventory/confirm-sale- Action: Confirm stock reservation (saga pattern step 2)
- Database: Inventory service finalizes stock deduction
- Why: Complete the distributed transaction
- Step:
- Response Propagation
- Orders -> Gateway -> Client
- Each service returns success/failure up the chain
- Orders -> Gateway -> Client
Mapping Backend Service Hops
Section titled “Mapping Backend Service Hops”This single checkout request touches:
- 4 services (Gateway, Orders, Products, Inventory)
- 3 schemas (
products,inventory,orders) inside a single PostgreSQL instance - 6 network hops (HTTP calls between services)
- 4 database queries (SELECT products, UPDATE inventory, INSERT orders, UPDATE inventory)
Without distributed tracing, debugging a slow checkout requires:
- Checking Gateway logs for the request
- Finding the correlation ID (if you remember to add one)
- Searching Orders logs for that ID
- Searching Products logs for that ID
- Searching Inventory logs for that ID
- Manually reconstructing the timeline from timestamps
- Guessing which hop was slow
With distributed tracing, you see the entire flow in one view:
- Visual timeline showing exactly where time was spent
- Automatic correlation across all services
- Database query durations highlighted
- Network latency between services is visible
By the end of Part 2, this canonical request will be fully observable—every hop traced, every query timed, every error contextualized.
The Current State of Logging
Section titled “The Current State of Logging”Currently, we try to manage this chaos with println!.
println!("Creating order for customer: {}", request.customer_email);// ...eprintln!("Failed to fetch product {}: {}", product_uuid, e);When things work, this is fine. When they fail, it’s a disaster.
The “Black Box” Problem
Section titled “The “Black Box” Problem”Imagine an order failing. You see this in the Orders Service logs: [ERROR] Failed to reserve stock for product a7f3c5...
But why? Was the Inventory Service down? Was it slow? Did it return to the 400 or a 500? To find out, you to check the docker logs for the Inventory Service container, guess the approximate timestamp (hoping clocks are synced), and grep for that UUID.
If the request touched 5 services, you are grepping 5 log files.
Structured Logging (A Half Step)
Section titled “Structured Logging (A Half Step)”We can improve this with structured logging using the tracing crate. Instead of just text, we log JSON objects with context.
info!( customer_email = %request.customer_email, item_count = request.items.len(), "Received order creation request");This gives us searchable fields (e.g., item_count > 5), but it still lacks causality. It doesn’t tell us that this log in the inventory Service was caused by that request in the Orders Service.
To solve this, we need Correlation IDs —a unique ID passed in HTTP headers (X‑Correlation‑ID) from service to service.
Gateway - generate and forward:
// Gateway creates a correlation ID for each incoming requestlet correlation_id = Uuid::new_v4();
// Forward it to the Orders Servicelet orders_response = state.http_client() .post(&orders_url) .header("X-Correlation-ID", correlation_id.to_string()) .send() .await?;Orders Service - extract and propagate:
// Orders extracts the correlation ID from the incoming request headerslet correlation_id = headers .get("X-Correlation-ID") .expect("Gateway must set X-Correlation-ID");
// And passes it along to the Inventory Servicelet inventory_response = state.http_client() .post(&inventory_url) .header("X-Correlation-ID", correlation_id.to_string()) .send() .await?;With correlation IDs, a single request can be traced across all services. When you search logs for a specific correlation ID, you’ll find entries in Gateway, Orders, and Inventory—the entire request flow in one place. Correlation IDs are the first step towards observability. They allow us to stitch logs together.
OpenTelemetry does not eliminate the concept of correlation IDs; it standardizes and automates them. Instead of manually passing custom X‑Correlation‑ID headers, OpenTelemetry automatically propagates context via W3C Trace Context headers (such as traceparent).
But even with correlation IDs, we are missing the time dimension. We know what happened, but we don’t know where the time went. Which service was slow? Did the delay happen during network I/O or database queries? Logs tell us events, but not durations.
Why Observability is Non-Negotiable
Section titled “Why Observability is Non-Negotiable”In OpenTel E-Commerce, a slow checkout could be caused by:
- Slow SQL query in Orders.
- Network latency between Orders and Products.
- Lock contention in Inventory’s database.
- Blocking operation in Gateway’s async executor.
Logs—even structured ones—are discrete points in time. They tell you what happened at specific moments, but they don’t show the continuous timeline between those moments. They don’t show the gaps. With correlation IDs, you know all the services involved, but not which one caused the delay.
This is why we need Distributed Tracing. Tracing turns those discrete log points into a continuous timeline. Instead of just events, traces record durations: how long did the request be spent on each service? How long was the network call? Tracing visualizes the request flow and automatically highlights bottlenecks. You see that the 2-second delay happened during the network call to Inventory, not during the database insert. You see that Inventory spent 1.8 seconds waiting for a lock, while Products only took 0.1 seconds.
Summary
Section titled “Summary”We have established our baseline:
- A Realistic Architecture: Independent services with strict boundaries.
- Real Complexity: Partial failures, distributed transactions, and network dependencies.
- The Observability Gap: We have logs, but we lack the ability to see the system as a whole.
The “chaos” is baked in. Now we need the tools to tame it. Correlation IDs help link requests across services, but they require manual implementation at every service boundary. Structured logging helps search for events, but it doesn’t capture timing. In the next chapter, , OpenTelemetry eliminates the manual work of passing correlation IDs by hand and measuring latencies with stopwatches. Instead, it instruments your code to automatically capture the complete request flow—which service called which, how long each step took, and when failures occur without changing your business logic.