Help LittleCart survive its first big sale
A system-design story you can reason through, challenge, and replay.
Alice wants a pair of headphones. She does not care whether we use Kubernetes, Redis, or a message queue. She cares that the page opens, the price is right, the item arrives, and her card is charged correctly.
Ben owns LittleCart, the shop selling them. He has a small engineering team and a limited budget. He wants to run a sale next month without turning every customer complaint into an emergency.
Maya is the engineer helping him. You are working beside her. Your job is to decide what the system needs as new problems appear.
We start with a shop small enough to understand. Each chapter changes that same shop. Keep asking: What happened to Alice? What caused it? What is the smallest useful change? What new problem does that change introduce?
The cartoons show the human problem. The technical maps show actual responsibilities. A smiling server in a drawing is a metaphor; a database transaction in the explanation has specific guarantees and limits.
All characters, incidents, measurements, IDs, and targets are fictional teaching examples. The local simulations model selected behaviors; they do not call AWS, a bank, or a real application. Product-specific behavior is linked to official documentation. No cloud deployment is required to use this book.
How to read: Work through chapters 1–6 to understand how a request reaches a scalable application. Chapters 7–10 protect the order. Chapters 11–14 explain delivery, diagnosis, and recovery. Chapter 15 asks you to put the whole design back together. Pause at each decision before opening the explanation.
1. Before drawing boxes, decide what a successful order means
“We need a shopping website,” Ben says.
Maya opens a blank page. “Imagine Alice has just paid. What are we promising her?”
Ben thinks for a moment. “That we have the headphones, that the amount is correct, and that the order is really saved.”
Those promises are the beginning of the design. A list of technologies cannot tell us whether we have kept them.
For our first release, Alice can browse products, sign in, add items to a cart, submit an order, complete payment, and check its status. Ben can update products and investigate an order. We will leave recommendations, loyalty points, and international warehouses for another release.
Now we need a few measurable agreements. Our fictional planning assumptions are 500 product API reads per second and 20 checkout submissions per second during a sale. We want 95% of product API responses to complete within 300 milliseconds at that load. We aim to accept valid orders within 500 milliseconds for 95% of requests, excluding the external payment process. These are targets to test, not performance promises we have already proved.
That distinction changes the interface. “We received your order” and “Your payment succeeded” are different statements. Alice may see an order number while payment is still pending. We must not display “Paid” merely because we saved an order.
There are also correctness rules, sometimes called invariants: conditions that must remain true as requests overlap and components fail. For LittleCart, available stock must not become negative; a retried submission must not create a second order for the same checkout intent; fulfillment must require a confirmed payment state. Each rule needs an enforcement point, not just a sentence in a specification.
“And if a Region fails?” asks Maya. Ben chooses initial planning targets of recovery within an hour and at most five minutes of order-data loss. Maya records those as business decisions requiring a recovery design and a drill. Payments made during any lost-data window will still need reconciliation with the payment provider.
Your decision: The payment provider takes eight seconds. Should our 500 ms order-acceptance target mean we claim payment succeeded early?
Open Maya's reasoning
No. Define a durable pending order and tell Alice its actual state. If the business insists on a final payment answer before continuing, agree a different end-to-end latency objective. Architecture starts with an honest product contract.
What you have designed: a set of promises that later choices must protect. Next we need the smallest system that can keep them.
2. Open the smallest shop that can do the job
Maya writes one application with separate catalog, cart, inventory, order, and payment modules. They share one deployment and one PostgreSQL database. This is a modular monolith: organized code without a network call between every business function.
Alice's browser asks the application for product P-42. The application reads PostgreSQL and returns the product. When she submits an order, the application checks her identity, validates the current price and stock, and writes durable order records.
The browser is the user interface running on Alice's device. The application enforces business rules on infrastructure we control. The database preserves authoritative records across application restarts. These jobs differ even if a prototype runs them all on one machine.
“Why not five microservices?” asks Ben.
“Because five services would give us five things to deploy and several new ways for checkout to fail,” Maya replies. “We can split a module later if independent scaling, release ownership, or isolation earns the extra work.”
This first map describes responsibilities, not a complete production setup. Before taking money, we also need HTTPS, authorization, backups, secret handling, monitoring, and the reliable payment process developed later. Small architecture does not mean missing controls.
We choose PostgreSQL because orders, line items, inventory reservations, and payment attempts have relationships and transactional requirements. We keep carts there initially too. We do not need a second database merely because carts are a different feature.
A cart expresses intent; it does not guarantee price or stock. Alice may leave a tab open overnight. Checkout must revalidate against authoritative data. A cart total calculated yesterday is not permission to charge that amount today without an explicit pricing policy.
Try explaining the boundary: If Alice changes a price in her browser's developer tools, why must the server ignore it?
Compare your explanation
The browser is controlled by the customer. The server must determine the authorized product, quantity, discounts, taxes, and currency using trusted rules. It can accept a product identifier and requested quantity, then calculate and present the actual payable total. Client-side validation improves usability; server-side validation protects the business.
We have a working concept. Now let us follow a real-looking request instead of adding boxes at random.
3. Alice types the address. Who answers first?
Alice enters https://shop.example.com. Before our application can handle anything, her device needs an address and a secure connection.
DNS is the naming system. A resolver obtains or reuses the answer for our hostname; Route 53 can publish that answer as our authoritative DNS service. DNS helps Alice find the front door. It does not carry her shopping basket through the system.
TLS protects a connection and lets the browser validate the endpoint's certificate for the hostname. We configure HTTPS on our public entry point and protect origin connections appropriately. A certificate service manages certificates; it is not a checkout-processing hop.
Our public entry point will be CloudFront, a content delivery network, or CDN. For now, think of it as a distributed front door that can serve eligible cached content and forward other requests. We will use its caching in the next chapter.
We associate an AWS WAF web ACL with that distribution. WAF, the web application firewall, can inspect HTTP requests for configured attack and abuse patterns. It is a policy enforcement point at the edge, not a replacement for our application's permission checks.
Alice's request follows a configured path from CloudFront to our application origin. In the later AWS design, that origin is an internal Application Load Balancer reached using a CloudFront VPC origin. This requires a supported Region, origin type, protocol configuration, and the documented networking prerequisites. S1
Maya gives Ben a useful diagnostic sequence: resolve the hostname, validate the certificate, inspect the HTTP response, then trace application processing. “The website is down” could mean failure in any of those layers. Restarting the app will not repair a missing DNS record.
Now Bob signs in and asks for Alice's order O-1001. His token is valid. The WAF sees an ordinary-looking request.
Your decision: Has he passed enough checks to view the order?
Inspect the missing check
No. Authentication establishes Bob's identity. Authorization must establish whether Bob may read O-1001. The application should constrain access by the authenticated customer or tenant and the permitted action. Guess-resistant identifiers reduce enumeration; they do not grant permission. This is the object-level authorization problem described by OWASP. [S2]
For Alice, this boundary means her order history remains private even when another customer knows an order number. For us, it means the security decision belongs beside the data access, not only at the front door.
4. The sale begins, and the photographs arrive slowly
Ben's promotion works. Alice opens a product page, but the headphones photograph takes several seconds to appear.
Maya checks the traffic. Our application keeps delivering the same image bytes to thousands of people. Nothing about those bytes is personal. We are spending application capacity on work that does not need our business logic.
We move public product images and versioned JavaScript and CSS files into S3, object storage. CloudFront can cache eligible copies near viewers. On a cache hit, an edge location serves the object without fetching it from our S3 origin again. That reduces origin work and can improve delivery latency; cache misses still need an origin fetch.
We keep the S3 bucket private and configure CloudFront Origin Access Control with an appropriate bucket policy. Public product content can be readable through our CDN while the bucket itself remains private. A regular S3 bucket origin is different from an S3 website endpoint. S3
Our distribution has different behaviors. /assets/* and /images/* use S3 with deliberate cache policies. /api/* goes to the application origin; shared caching is disabled initially. API requests can still pass through CloudFront when they are not cached.
“Why don't we cache everything?” Ben asks.
Because Alice's order response is not the same resource as Bob's order response, even if both use a similar URL pattern. A shared cache configured without the correct identity boundaries can leak private data. Our starting policy avoids shared caching for account, cart, checkout, and order endpoints. We also review response cache headers and error-caching behavior.
Disabling caching is not the same as forwarding every required header. The origin request policy must pass the authentication information, query strings, and cookies that the application needs. Cache keys and forwarded request information have separate purposes. S4
For static assets, versioned names help with freshness: app.abc123.js identifies one build, while a changed build gets a new name. The HTML entry document needs its own freshness policy so Alice can discover that new build.
Predict the result: The second request for an unchanged public photograph hits the edge cache. Does PostgreSQL need to run a product query just to return those image bytes?
Follow that request
No. That asset request can end at the CDN. A separate product API request may still reach the application and PostgreSQL. A page is assembled from several requests; there is no rule that every request must visit every component.
What to verify: Compare CDN hit and miss responses, confirm direct unauthorized bucket access fails, and test Alice and Bob's private responses separately. The user-visible result should be faster public assets without cross-customer exposure.
5. The pictures are fast. The application is still overloaded
The asset change helps, but product API latency now climbs during the sale. Maya profiles the application. Its CPU is saturated handling legitimate application work. The database has headroom in this fictional incident.
We could buy a larger machine: vertical scaling. That can be a sensible first action. Eventually, though, one machine has a capacity ceiling and remains one failure point.
Maya adds another application instance and places an Application Load Balancer, or ALB, in front. The ALB routes incoming application requests to configured targets. If we configure useful health checks and routing, the instances can share traffic.
Alice's next request might reach instance B even though her earlier request reached A. We discover that her login session was stored only in A's memory. On B, she appears logged out.
This is why the application needs a deliberate stateless request-handling design. Important cross-request state belongs in an appropriate shared store or verifiable session mechanism. Local memory may hold disposable data; it must not be the only record of Alice's login, cart, or accepted order. Sticky routing can hide the problem until the selected instance fails.
More instances also create more connections and competing requests to PostgreSQL. If each of 12 instances permits 30 database connections, we have allowed up to 360 connections. That arithmetic does not prove the database can use them efficiently. We establish a connection and concurrency budget, then measure.
Our fictional load target of 500 requests/second with a mean time in the system of 0.1 seconds implies about 50 requests in flight under steady conditions. This is a planning relationship, not evidence that one instance or one pod can handle 50 requests. Slow queries and queueing can change the picture quickly.
Your decision: CPU is low, database lock waits are high, and latency is rising. Should we immediately double the application count?
Check the bottleneck
Probably not. More callers may increase contention on the same database. Find the blocking transaction, query pattern, connection pressure, and workload first. Scaling helps only when it adds capacity to the limiting resource or removes demand from it.
We have learned two connected lessons: requests can move between instances, and scaling one layer can overload the next. Now we need somewhere reliable to run those instances.
6. Where does the application run, and who keeps it running?
“Are instances, containers, pods, and EKS four different applications?” Ben asks.
No. They describe different layers of execution and management.
A container image packages our application and its runtime dependencies. Running that image creates a container process with configured isolation and resources. The image is not a virtual machine and does not provide its own independent host kernel.
In Kubernetes, a pod is the scheduling unit containing one or more containers. A node supplies compute on which pods run. A Deployment describes the desired application replicas and update behavior. A Service gives selected pods a stable access abstraction while individual pod addresses change.
EKS provides a managed Kubernetes control plane. We still own application behavior, permissions, resource settings, workload security, and the operational responsibilities of our selected compute model. The Kubernetes API and controllers manage the runtime; customer requests do not need to pass through the Kubernetes API server. S16
For this book, the engineering organization already operates Kubernetes, so LittleCart uses EKS. If our small team did not have that capability, ECS with Fargate could be a reasonable starting point. Kubernetes earns its place through an operating need, not the number of boxes in a diagram.
We configure a supported AWS load-balancer integration. With IP targets in this example, the ALB can route to registered application pod IPs. A Kubernetes Ingress is configuration consumed by a controller; it is not automatically another proxy process in the request path. Target mode, controllers, and networking determine the actual route. S17
We run replicas across at least two Availability Zones and configure scheduling so the placement matches the intent. “Three replicas” alone does not prove they occupy different nodes or AZs.
The app and database use private network paths inside a VPC, our regional virtual network. A subnet belongs to an AZ. Routing decides where traffic can go; security groups restrict permitted network relationships. Private addressing does not establish customer authorization or workload trust. Application-to-database access also requires database credentials and privileges.
We give the application only the cloud permissions it needs using workload identity and scoped IAM roles. The public ALB path, internal data paths, and outbound provider calls need separate decisions. A NAT gateway can provide outbound IPv4 internet connectivity where configured; it is not an application-aware security filter.
Kubernetes now notices that one pod has crashed and replaces it. But the replacement starts slowly.
Your decision: Should the new pod receive checkout traffic immediately because its process exists?
Separate the health questions
No. A startup probe can allow initialization time. Readiness indicates whether the pod should receive Service traffic. Liveness can trigger container restart after configured failures. Those probes ask different questions. Making liveness fail whenever the shared database is unavailable can cause a restart storm without repairing the database. [S5]
The Horizontal Pod Autoscaler can change workload replica counts using configured metrics. It does not instantly supply node capacity, fix slow SQL, or guarantee the payment provider can take more calls. Establish realistic resource requests, capacity provisioning, scale limits, and dependency budgets. S6
What Alice gains: one failed application process need not end her shopping session. What the team takes on: orchestration, placement, networking, and deployment behavior that must be understood and tested.
7. Everyone keeps asking PostgreSQL the same question
After application scaling, Maya sees a new bottleneck: thousands of repeated reads of the same product description. Each response is small, but the repetition is expensive.
This is where a cache may help. We add Redis or Valkey as a disposable store for frequently read catalog data. The application checks product:P-42:v1. On a hit, it uses the cached representation. On a miss, it reads PostgreSQL and may populate the cache with a defined expiry.
CloudFront and this application cache solve related but different problems. CloudFront can serve eligible whole responses or objects near viewers. The application cache helps application code avoid repeated data-store work. An edge cache hit might avoid the app entirely; an application cache hit still involves application execution.
“Can we use the cached stock count to accept orders?” asks Ben.
That would let a stale copy decide a scarce-resource allocation. We can show an approximate availability label while browsing, but checkout must use the authoritative reservation rule in the database. The cache is a convenient copy, not the stock ledger.
We need a freshness policy. A time-to-live bounds how long a particular cached value may remain under normal behavior; it does not provide instant synchronization with every database change. On product updates, we can invalidate or replace relevant entries, while accounting for races and failed invalidations. The final price is revalidated at checkout.
A cache outage creates another question. If every application instance simultaneously falls back to PostgreSQL, the sudden demand may overwhelm it. We cap concurrency, use bounded fallback behavior, and consider serving safe stale public catalog data. We do not serve stale authorization decisions or authoritative payment state simply to preserve a green dashboard.
For one hot item, many simultaneous misses can create a cache stampede: everyone asks the database for the same replacement value. Request coalescing, controlled refresh, and varied expirations can reduce that surge. Each needs a failure policy and measurement.
Try the arithmetic: At 500 product requests/second, a simulated 80% hit rate leaves 100 misses/second. If each miss performs four queries, that is about 400 queries/second for this path, before other traffic. At 0% hits, it becomes 2,000 queries/second. A successful warm-cache load test alone tells us little about a cold restart.
When should you add this component?
When measurements show repeatable, cacheable work is a meaningful cost or bottleneck and the freshness rules are acceptable. First check query plans, indexes, payload size, and unnecessary calls. A small application with efficient queries may need no separate cache at all.
Browsing is now smoother. But faster reads cannot solve the most important sale problem: two customers want the last pair of headphones.
8. Alice and Bob both see “1 left”
Alice clicks Buy. Bob clicks Buy almost simultaneously. Both browsers previously saw one item available.
Here is the broken approach: read stock, check that it is positive in application code, then later write an order and a reduced stock count. Both requests can read the same original value before either commits a change.
Maya moves the enforcement into the authoritative database transaction. For a single inventory row, a conditional update can reserve one unit only if enough stock remains:
-- PostgreSQL teaching fragment; parameters belong to the application driver.
UPDATE inventory
SET available = available - 1
WHERE sku = 'P-42' AND available >= 1
RETURNING sku, available;
If one row is returned, this statement reserved one unit. If no row is returned, do not claim success. Under PostgreSQL's Read Committed behavior, competing updates to that row wait as required and re-evaluate the condition on the updated row. Isolation and statement design matter. S7
This fragment is only the critical operation, not a complete order implementation. Within one transaction, our application must also claim a unique checkout intent, create the order and payment-attempt records, record the reservation and its expiry, and write the later-work record introduced in chapter 10. If any required step fails, it rolls back. Multi-item carts need consistent lock ordering or another deliberate concurrency strategy, plus deadlock and conflict handling.
We create a durable idempotency key for Alice's checkout intent, scoped to her account and the operation. A database uniqueness constraint coordinates concurrent submissions across application instances. Store a request fingerprint and reject incompatible reuse of the key. The application must handle the “already in progress” case as well as returning a completed earlier result.
Disabling the Buy button can reduce accidental clicks, but cannot prevent a mobile-network retry, an app restart, or two requests sent concurrently. The guarantee must survive those conditions on the server.
Reservations also have a lifecycle. Reserving decreases available-to-promise stock; successful payment converts the reservation into committed allocation without subtracting it again. A terminally failed or expired reservation can release stock exactly once using a guarded state transition. Expiry must not race blindly with a payment whose outcome is still unknown.
Your decision: Alice's first response is lost. Her browser retries with the same checkout key. Should we reserve a second unit?
Inspect the intended result
No. The existing checkout intent identifies the same operation. Return or recover its existing order state. This needs durable uniqueness and an atomic transaction boundary, not a per-pod memory map. A genuinely new purchase uses a new intent after the interface makes that distinction clear.
How to prove the rule: In an isolated test, start with one available unit and submit concurrent distinct checkout intents. Exactly one reservation should succeed. Then replay the winning intent and verify that order count and reserved quantity do not increase. These are expected assertions; no real application test was performed for this book.
Alice has a durable pending order now. We still owe her an honest answer about payment.
9. The payment times out. Was Alice charged?
Our worker sends a request to the payment provider. The provider processes it. The network drops the response.
From LittleCart's point of view, all we know is that we did not receive an answer. A timeout describes our observation. It does not prove the payment failed.
If we create a new payment operation immediately, Alice could be charged twice. If we tell her the order failed and release stock immediately, a successful late payment could belong to an order we have already cancelled.
Maya creates a stable payment-attempt ID tied to O-1001 and a stable provider idempotency key for that attempt. A retry follows the provider's documented API semantics using the same key and compatible parameters. Provider rules differ by API and retention window; Stripe, for example, documents different details for its API versions. A key is not an unlimited guarantee that can be reused forever. S8
Our local order can remain PAYMENT_PENDING while a payment attempt is UNKNOWN. A bounded reconciliation process queries the provider's authoritative status or consumes a verified webhook. Reconciliation means comparing our records with external evidence and resolving the difference according to defined rules.
Some payment methods require Alice to complete additional authentication. Model an explicit action-required state and send her through the provider's approved flow; a background worker cannot complete that user action for her. Use a suitable tokenized integration and avoid handling raw card details in our application. The worked timeout below assumes the provider has enough authorized information to process the attempt.
A webhook is an inbound event notification from the provider. We verify its signature using the provider's documented method, check the associated merchant, payment identifier, amount, and currency, and handle duplicate or out-of-order delivery. An unverified JSON field saying paid: true cannot authorize fulfillment. S9
We persist validated webhook work before acknowledging it when the design requires durable processing, then apply guarded state transitions. One transaction can record a processed-event identity alongside the local change. Distinct provider events can still describe the same payment, so event-ID deduplication alone is not enough; business-state checks matter too.
Do not hold a database row lock open while waiting eight seconds for a bank. We commit local intent first, perform external work with bounded timeouts, and reconcile the resulting state. There is no ordinary PostgreSQL transaction that automatically rolls back a payment already accepted by an external provider.
If payment eventually fails conclusively, we release the reservation through its guarded transition. If it succeeds after a reservation has legitimately expired, we need an explicit business exception path: reacquire stock if allowed, refund, or send the case for operator resolution. Hiding that race does not make it disappear.
Your decision: The provider times out. Pick the safest message for Alice: “Payment failed,” “Payment succeeded,” or “We are confirming your payment; do not pay again yet.”
Connect the screen to the system state
Use the pending message while the outcome is unknown, with an order reference, status-check path, and support policy. A useful interface expresses uncertainty honestly and prevents unnecessary repeat payment attempts. It must also have a bounded operational resolution process; “pending forever” is not a successful design.
We have protected money and stock. Next, we need to make sure the work after checkout actually happens.
10. The order exists, but the confirmation never arrives
The original checkout function did everything in one request: save the order, contact the provider, create an invoice, send email, update analytics. A slow email service made Alice wait even when her order was already durable.
We move non-immediate tasks to a worker, an application process that handles background work. A queue stores work waiting to be handled. This separates how quickly work arrives from how quickly downstream systems can complete it.
“So we save the order, then send a queue message?” asks Ben.
Maya stops him. There is a crash gap. If we commit the order and crash before publishing the message, the order exists but no worker learns about it. Publishing first creates the opposite risk: a message about an order that never commits.
We add an outbox table in the same PostgreSQL database. The order transaction writes its records and an outbox event together. A relay later publishes committed outbox events to the queue. This makes the business change and the intent to notify atomic within that database transaction; it does not make the database and queue one distributed transaction. S10
The relay can publish a message and crash before recording that publication. On restart, it may publish again. SQS standard queues can also deliver a message more than once. Workers must tolerate duplicates. S11
For a local database effect, a processed-event record and the effect can commit together. For an external email send, a crash after sending but before recording success still leaves ambiguity. Use provider idempotency or a durable dispatch design where available, and make the customer-facing consequences of occasional duplicates explicit. “We use a queue” is not proof of exactly-once business effects.
Workers acknowledge or delete queue work after their durable processing responsibility is complete. A visibility timeout temporarily hides received work from other consumers; if processing is interrupted, it may become visible again. Retry transient errors with bounds and jitter. Move poison messages to a dead-letter queue after a controlled policy, alert an owner, fix the cause, and replay carefully.
Now the email provider slows down. The queue grows. Alice's order acceptance can remain responsive within the system's capacity and admission limits, but confirmation is delayed. We monitor the age of the oldest work, not only the count. Ten jobs stuck for an hour can matter more than a thousand jobs that clear in seconds.
Queues buffer work; they do not create unlimited capacity. If we accept 20 jobs/second but finish 15, the backlog grows by five jobs/second. We must increase safe throughput, reduce demand, degrade a nonessential feature, or stop promising immediate completion.
Pause at the crash: The worker sends an invoice request, then crashes before deleting its queue message. What must the next worker assume?
Reason about redelivery
The work may already have taken effect. It should use the stable business operation ID and provider evidence, rather than blindly creating another invoice. A message receipt and a business transaction are different boundaries. The retry strategy must match the effect being performed.
For our first sale, SQS and a small number of workers are sufficient teaching choices. Kafka becomes a separate evaluation if retained event streams, multiple independent consumers, partition ordering, or replay requirements justify it. We do not add a streaming platform merely because checkout has background work.
11. Ben asks for search, uploads, and “some AI”
The sale survives. Ben now wants customers to find “wireless headphones under 2,000 baht,” upload review photos, and ask an AI assistant for recommendations.
Maya returns to the same method: determine the user problem, identify who owns the truth, then choose the smallest useful capability.
For a modest catalog, PostgreSQL search and suitable indexes may be enough. If relevance ranking, typo tolerance, facets, or volume exceed that design, we can maintain a separate search index such as OpenSearch. The index is a derived view, so it can lag. Search may show an item whose stock changed a moment ago; checkout still checks authoritative availability. We also need index rebuilds, indexing-failure handling, and product-deletion propagation.
For photographs, the application should not keep large uploads in a pod's temporary filesystem and hope they survive rescheduling. We use object storage. Alice requests an upload authorization; the application authenticates her and chooses an allowed object key. She uploads to a quarantined location using a short-lived presigned mechanism constrained to our requirements. A presigned POST policy can constrain properties such as permitted size ranges; content inspection still has to verify the actual bytes. S12
Only validated files become available through the intended delivery path. A claimed content type is not proof that an upload is a harmless image. Upload permission also does not mean permission to read every private object in the bucket. Object access must preserve ownership and sensitivity boundaries.
The optional AI assistant is another caller with limited authority. It may search approved catalog information and explain product differences. It does not invent stock, approve refunds, modify payment state, or trust an uploaded review as an instruction. Tool authorization and business validation remain enforced outside model-generated text. If the model is unavailable, Alice should still be able to buy headphones.
Your decision: Search says P-42 is available, the cache says one remains, and PostgreSQL says zero. Which answer controls the new reservation?
Choose the authority
The authoritative inventory transaction controls allocation. Search and cache improve discovery and performance. Their usefulness depends on tolerable staleness; they cannot silently replace the source of truth for a scarce item.
Each addition has an owner and an exit test. Can we rebuild the index? Can we remove an abusive upload? Can checkout continue if recommendations fail? These questions keep optional features from becoming accidental critical dependencies.
12. Maya fixes a bug. How does the fix reach Alice safely?
Maya finds a rounding bug in a discount calculation. Editing her laptop does nothing for Alice. We need a controlled path from source code to the running application.
(images/09_operations_story.png)
First, Maya opens a pull request. Tests check the changed price calculation, including currency and boundary cases. Reviewers inspect behavior and security implications. Secret scanning, dependency checks, and relevant static analysis add evidence; they do not replace the tests or human judgment.
After approval, continuous integration, or CI, builds a container image and records its immutable digest. A registry such as ECR stores that image. We promote the same built artifact through environments, supplying the intended configuration separately. Rebuilding for production could produce different bytes from what we tested.
The CI workflow uses restricted permissions and short-lived cloud credentials through a configured OpenID Connect (OIDC) trust relationship, instead of relying on a permanent broad AWS key. The trust policy must constrain which repository and approved branch or environment can assume the role. Untrusted pull-request code must not get deployment credentials. S13
Terraform describes cloud resources such as networks, load balancers, databases, and IAM roles. Its plan helps reviewers assess intended changes; applying an approved change updates infrastructure. Its state can contain sensitive data and needs protected storage and access. Terraform does not inspect and approve Alice's checkout requests.
For our Kubernetes deployment, Helm packages and renders Kubernetes configuration with values. It is not a container registry. Argo CD compares the desired deployment configuration in Git with the cluster and reconciles according to its configured sync policy. Automatic sync, self-healing, and pruning are separate choices with operational consequences. S14
The production configuration points to the reviewed image digest. Argo CD applies it; Kubernetes manages the workload update; the traffic integration sends requests to eligible targets. This is the delivery path. Alice's runtime request does not pass through GitHub, Terraform, Helm, or Argo CD.
We first expose a limited, measured portion of traffic to the change using a deliberately configured canary mechanism. Pod counts alone do not guarantee an exact traffic percentage. We compare errors, latency, checkout outcomes, and enough representative traffic before expanding. Missing telemetry or too few orders is an inconclusive result, not permission to declare success.
Rollback also depends on data compatibility. Suppose the new app renames a column and the migration deletes the old one. The old image may no longer run. We prefer an expand–migrate–contract sequence: add compatible structure, deploy code that works during transition, backfill and verify, then remove obsolete structure after old consumers are gone. A feature flag can stop a behavior, but cannot automatically undo an irreversible data change.
Your decision: The new release starts successfully, but half the valid coupon orders now fail. Is “all pods Running” enough evidence to continue?
Judge the release by the customer promise
No. Process health is necessary but incomplete. Stop expansion, disable or roll back the faulty behavior where safe, and preserve diagnostic evidence. Validate the business outcome, including amounts and state transitions, rather than only successful container startup.
A safe release is a system-design concern because changing the system is one of the ways we can break it.
13. At 10:03, Alice says checkout is stuck
The on-call engineer opens a dashboard. CPU is normal. All pods are Running. Alice still has no final payment result.
Maya asks for her order reference. O-1001 links the customer complaint to the order, payment attempt, and background workflow. A trace ID follows one execution; durable business IDs connect separate retries and asynchronous executions. We need both kinds of correlation.
Metrics reveal patterns: checkout acceptance errors, latency percentiles, payment-pending age, reservation expiry, queue age, and provider timeout rates. Logs describe specific events and decisions. Traces show time spent across instrumented calls. Audit records establish who changed permissions, configuration, or business state.
We avoid writing secrets, full payment details, raw tokens, or unnecessary personal data to those records. We also avoid using individual order IDs as metric labels that create unbounded cardinality; order IDs belong in appropriately protected logs and traces.
For this incident, our fictional timeline is: O-1001 committed at 10:03:01, its payment request timed out at 10:03:04, a verified provider event arrived at 10:03:09, and a database lock blocked the state update until 10:03:27. The right investigation is the lock and pending-payment workflow. Scaling the web pods is not supported by that evidence.
We define a service-level indicator, or SLI, for eligible order acceptance: successful durable acceptances divided by valid eligible submissions. Our illustrative monthly SLO, or service-level objective, is 99.9%. Payment-finalization time and correctness need separate measures; excluding them from one latency target does not make them irrelevant to the customer.
If 100,000 eligible submissions occur in a measurement window, a 99.9% request-success target permits 100 unsuccessful submissions in that denominator. Do not translate that directly into downtime minutes. A request-based objective and a time-based availability objective measure different things.
Alerts should point to action. “Pending payments older than the allowed resolution threshold” calls for inspecting provider status, webhooks, workers, and state transitions. A generic CPU alarm alone does not tell the engineer which customer promise is at risk.
Your decision: The payment dashboard has no samples for the last ten minutes. Should the release controller treat its error rate as zero?
Handle missing evidence
No. Missing data can mean broken instrumentation, a stopped worker, or no representative traffic. Treat it as unknown and apply the defined hold or investigation policy. An empty graph is not evidence of successful payments.
The goal is not to collect every possible log. It is to answer: What did Alice ask us to do, what became durable, which dependency outcome is known, and what is the next safe action?
14. One AZ fails. Later, the database is restored from backup
Ben asks whether three replicas mean we are disaster-proof.
Maya presents two different incidents. In the first, one Availability Zone fails. In the second, someone deletes important data and the deletion replicates successfully.
For the AZ failure, application placement, load-balancer coverage, database failover capability, and surviving capacity all matter. Three application pods in one AZ are not an AZ-resilient deployment. Even correctly spread pods cannot serve traffic if the only remaining critical dependency is unavailable.
For the deletion, additional replicas may faithfully copy the mistake. High availability keeps the live service accessible through selected failures. Backups and recovery restore an earlier state. We need both according to the promises in chapter 1.
Our one-hour RTO is a target for restoring service after the defined disaster. Our five-minute RPO is the maximum acceptable data-loss window for the covered data. Neither is a measured result until we exercise the actual recovery procedure. S15
The drill restores the database into an isolated recovery environment, obtains the required encryption keys and secrets through controlled access, starts compatible application versions, and checks order consistency. Recovery includes infrastructure, artifacts, configuration, identity, networking, DNS changes where required, and operator access. A database snapshot by itself cannot run the shop.
Then we face a payment-specific problem. Suppose a restored database has no record of O-1001, but the provider processed its payment after the recovery point. The bank did not roll back with our database. We reconcile external payment records and durable references before allowing actions that could charge or fulfill again.
The same caution applies to queues. Recovered order data and existing queued events can represent different moments. We pause or gate consumers during controlled recovery, decide how to replay, and validate deduplication and state compatibility. Blindly starting every worker can make inconsistency worse.
We also test a cold cache and a rebuilt search index. Neither should be the only copy of an accepted order. If the shop cannot reopen without a cache that was described as disposable, we have discovered an undeclared dependency.
Your decision: A backup job succeeded last night. Can Ben tell customers we can recover within one hour?
Separate a backup from a recovery result
No. The backup's existence does not establish restore time, usable keys, compatible application code, integrity, or reconciliation. Run the drill, measure elapsed recovery time and the actual data gap, record defects, and repeat after fixing them. Targets must be supported by evidence.
We keep one primary Region with multiple AZs for this example. A second Region may support disaster recovery if justified and implemented. Active-active regional writes would add conflict resolution, cross-region latency, data placement, and payment coordination. We would need a requirement strong enough to justify those costs.
15. Replay Alice's purchase without looking at the boxes
Alice opens the shop. Can you tell the story from her screen to a confirmed order?

(images/10_complete_runtime.png)
Read this map as related request and work paths. The application workloads share EKS management; each arrow still has its own protocol, permissions, and failure behavior. Verified provider webhooks enter through the configured public API path, and reconciliation also queries the provider; those return routes are described in chapter 9. Worker database access persists guarded outcomes. DNS lookup, delivery, and observability are explained in chapters 3, 12, and 13 respectively.
Start with naming and transport. DNS helps her device locate the public endpoint. HTTPS protects the connection. CloudFront serves eligible public assets and forwards the API request under the configured policy. The associated WAF evaluates configured rules. The origin path reaches our internal ALB and a ready application target.
The application authenticates Alice and authorizes her action. Browsing can use disposable catalog copies. Checkout calculates the authoritative payable amount and uses the database transaction to claim her checkout intent, reserve stock, save the order, and record work in the outbox. The acceptance response identifies O-1001 and its honest pending state.
The outbox relay and queue carry committed work to workers. A stable payment attempt reaches the provider under its idempotency contract. A known result, verified event, or reconciliation resolves the attempt. Guarded local transitions confirm the order and protect reservation accounting. Fulfillment and notification proceed under their own retry and deduplication rules.
At every stage, metrics and correlated records help an operator explain what happened. A new image digest reaches the running system through review, CI, approved configuration, and reconciliation. Recovery can rebuild the service and reconcile external effects if live data is lost.
Do not recite this as a fixed route that all packets follow. An image-cache hit ends at CloudFront. A cached catalog read may not query PostgreSQL. A background email never needs to start in Alice's browser. A deployment changes the runtime but is not a runtime request hop.
The component belongs only if you can complete this sentence
“We added ___ because ___ was happening; it changes ___ for Alice; we will know it helped when ___; its new failure mode is ___.”
For example: “We added a worker queue because email delivery was delaying request completion. Alice can receive durable order acceptance while notification continues. We will measure acceptance latency and notification age. We now need backlog limits, duplicate-safe effects, and an owner for failed jobs.”
That explanation is more valuable than saying, “Modern systems need queues.”
Your final design review
Explain these five incidents to another engineer, including what you would inspect before changing infrastructure:
- Alice's second submit request arrives at a different pod after the first response is lost.
- Bob requests Alice's order using a valid Bob session.
- The payment provider accepts the payment, but its response never reaches us.
- The outbox relay publishes successfully and crashes before recording publication.
- A database restore loses local order records while external payments still exist.
Review the expected reasoning
For 1, use durable checkout identity and uniqueness across pods; recover the existing result. For 2, enforce object and action authorization using the authenticated principal. For 3, preserve unknown state and reconcile under the provider's contract. For 4, expect duplicate publication and make downstream effects safe. For 5, control worker restart and reconcile payments and events against the recovered state.
A strong answer names the authority, the atomic boundary, the ambiguity, the evidence, and the safe next action. Naming a product without those details is incomplete.
You now have a connected design to implement and challenge. The next step is to make a small version real, inject the failures, and compare what happens with what you predicted.
Practice: build evidence in six small sessions
This is an implementation exercise plan, not a claim that a supplied application has been deployed or tested. Use a local sandbox and a fake payment adapter; no production credentials or real charges are needed. The SQL earlier is a reviewed teaching fragment, not a complete migration or runnable service.
| Session | Change one thing | Evidence that teaches you something |
|---|---|---|
| 1. A real order | Build the modular application and PostgreSQL schema; save an order and read it back after an app restart | Accepted orders persist; browser-supplied price changes are rejected or recalculated |
| 2. Two callers | Add durable checkout intent and guarded inventory updates | Concurrent buyers cannot reserve more than stock; repeated intent returns the original order |
| 3. A slow dependency | Make the fake payment adapter accept a request and drop its response | The UI reports pending, the attempt is reconciled, and the recorded financial effect is not repeated |
| 4. The crash gap | Commit outbox events, publish through a relay, and interrupt it after publishing | Duplicate delivery occurs without an additional local business effect |
| 5. Two app copies | Run two instances, then stop one during browsing and submission | Shared state and retry behavior survive; any in-flight failure is visible and recoverable |
| 6. A recovery | Restore a backup into a separate environment and compare against fake external payment records | Measure recovery time, find mismatches, and resolve them before enabling further processing |
Keep a prediction, observed result, and explanation for each session. If the observed result differs, that is the most valuable part of the exercise. Clean up test data and any optional cloud resources when finished.
A map from symptoms to decisions
| What the user experiences | First question | Candidate change | Evidence required before calling it fixed |
|---|---|---|---|
| Public images are slow | Are we repeating origin delivery of identical content? | Object storage and CDN policy | Hit/miss behavior and viewer latency; private origins stay restricted |
| Requests wait under load | Which resource is limiting throughput? | Query repair, caching, capacity, or admission control | Representative load and dependency saturation measurements |
| Login disappears | Is important session state local to one instance? | Deliberate shared or verifiable session design | Switch instances and remove one during the flow |
| Two buyers get the last item | Where is allocation enforced atomically? | Transactional conditional reservation | Concurrent test and database invariants |
| A retry creates another order | Is intent identity durable and unique? | Scoped idempotency record and constraint | Lost-response and concurrent-retry tests |
| Payment seems stuck | Is the outcome unknown or conclusively failed? | Stable attempt, verified events, reconciliation | Provider evidence and bounded resolution time |
| Email delays checkout | Must this effect complete before acceptance? | Outbox, queue, and worker | Durable acceptance plus measured background-work age |
| New code breaks coupons | Did validation cover business outcomes? | Better tests and guarded rollout | Representative checkout correctness and release comparison |
| Recovery loses recent orders | Which external effects outlived our database state? | Recovery reconciliation | Restore drill with payment and event consistency checks |
Optional choices: when the answer may change
| Choice | Our reason here | Revisit when |
|---|---|---|
| Modular monolith | Small team and transactional business logic | Independent teams or workloads need separate release and scaling ownership |
| PostgreSQL for core state | Relationships, constraints, and local transactions | Measured access patterns or data volumes justify another store and its consistency model |
| EKS | The fictional organization already operates Kubernetes | A simpler managed runtime reduces operating work without losing required capability |
| SQS | Durable background work with controlled consumers | Retained event streams and independent replay requirements justify a streaming platform |
| Application cache | Measured repeated public catalog reads | Efficient direct reads are sufficient, or consistency costs exceed the benefit |
| Search index | Added only for search requirements beyond the first design | Catalog scale, relevance, or facets exceed the chosen database search approach |
| Single primary Region | Simpler ownership and write consistency | Business recovery, geography, or legal requirements justify a different regional design |
Official references and further reading
References support product behavior; LittleCart's incidents and decisions are worked examples. Review the current documentation for your selected product versions, Region, and operating model before implementation. Documentation reviewed on 23 November 2026.
- S1 — AWS, CloudFront VPC origins: private origins, supported resources, and networking prerequisites. https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-vpc-origins.html
- S2 — OWASP, Broken Object Level Authorization: object-level checks for authenticated callers. https://api-security.owasp.org/editions/2023/en/0xa1-broken-object-level-authorization/
- S3 — AWS, S3 origin access: Origin Access Control and bucket-origin distinctions. https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
- S4 — AWS, origin request policies: forwarded information versus cache keys. https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html
- S5 — Kubernetes, probes: startup, readiness, and liveness behavior. https://kubernetes.io/docs/concepts/workloads/pods/probes/
- S6 — Kubernetes, Horizontal Pod Autoscaling: metric-based replica control. https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/
- S7 — PostgreSQL, transaction isolation: concurrency behavior under selected isolation levels. https://www.postgresql.org/docs/current/transaction-iso.html
- S8 — Stripe, idempotent requests: API-specific retry semantics. https://docs.stripe.com/api/idempotent_requests
- S9 — Stripe, webhooks: verification and delivery behavior. https://docs.stripe.com/webhooks
- S10 — AWS, transactional outbox: dual writes and duplicate notifications. https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html
- S11 — AWS, SQS at-least-once delivery: consumers must tolerate duplicates. https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues-at-least-once-delivery.html
- S12 — AWS, POST policy: conditions for presigned browser uploads. https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-HTTPPOSTConstructPolicy.html
- S13 — GitHub, OIDC with AWS: short-lived authentication and trust-policy scope. https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws
- S14 — Argo CD, automated sync: synchronization, self-healing, and pruning settings. https://argo-cd.readthedocs.io/en/stable/user-guide/auto_sync/
- S15 — AWS, DR objectives: RTO and RPO definitions. https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/disaster-recovery-dr-objectives.html
- S16 — AWS, EKS security: shared responsibility and workload isolation. https://docs.aws.amazon.com/eks/latest/userguide/security.html
- S17 — AWS Load Balancer Controller: target modes and routing configuration. https://kubernetes-sigs.github.io/aws-load-balancer-controller/latest/guide/ingress/annotations/









Top comments (0)