Part 1 of How Backend Systems Scale →

From Code to Service: Requests, APIs, and Web Servers

15 min readUpdated

Part 1 of the eight-part How Backend Systems Scale series. Keep the separate powers-of-ten estimation reference nearby for the calculations.

You write a function that creates an order. It checks the cart, saves the purchase, and returns an order ID. The tests pass.

Then a customer clicks Buy, waits a few seconds, and clicks again. There are now two orders.

Nothing in the function’s tests required it to recognize two requests as the same purchase attempt. That requirement appeared when another computer started calling it over a network.

This is where we’ll begin. Before adding servers, caches, or shards, we need to understand what changes when ordinary code becomes a service.

The examples in this series move between a store, a photo-sharing app, and a background-job service. You only need basic programming knowledge. Traffic figures are teaching assumptions; we’ll keep them visible rather than present them as measurements of real companies.

On this page

Build the service contract

Start with one request

A browser wants to show product 42. Your program already knows how to find that product. We need an agreed way for the browser to ask it to do so.

For example, the browser could send GET /products/42. The program finds the product and returns a JSON response:

We now have a few names for the roles in that exchange:

  • The browser is a client: it asks for work.
  • The receiving program acts as a server: it performs the work and responds.
  • Their API defines the request, the response, and the errors both sides should expect.

A service keeps offering that capability as requests arrive. “Server” describes a role here, not necessarily a separate physical machine. Later, several machines may run copies of the receiving program.

Describe behavior before choosing tools

A product lookup sounds simple until the product has been removed. Or the caller isn’t allowed to view it. Or the store needs to answer a hundred requests every second.

These decisions belong in the contract:

KindQuestionStore example
FunctionalWhat can someone do?View products and place orders
Quality or capacityHow well must it work?Handle a stated peak with an agreed response-time target

“Must scale” leaves us guessing. “Handle 100 product reads per second within our agreed response-time target” gives us something to test. We can revise the assumption when we know more.

CRUD gives us a useful starting vocabulary

Our first endpoint reads a product. Store administrators also need to create products, change them, and remove them.

Those four operations give us the name CRUD: create, read, update, delete. HTTP methods often express them, although this isn’t a strict one-to-one mapping:

OperationExample APIMeaning
CreatePOST /productsAdd a product
ReadGET /products/42Retrieve a product
UpdatePATCH /products/42Change part of a product
DeleteDELETE /products/42Remove a product

The endpoint names are only part of the design. For each operation, decide:

  • Who may perform it.
  • Which input is valid.
  • How a missing record is reported.
  • What repeating the request should do.

That last question matters even when traffic is small.

Memory is not durable storage

Suppose the first version keeps orders in a dictionary. It works until the process restarts. The dictionary starts empty, and the orders are gone.

We need the records to survive the process that handled the request. For this store, a database provides durable storage:

  • Temporary calculations can remain in application memory.
  • Orders go into the database.
  • The server returns success after the required database changes commit.
  • Backups and restore procedures cover the recovery scenarios we need to tolerate.

A commit and a backup serve different purposes. Committing an order doesn’t give us a historical copy we can restore after an accidental deletion.

The first difficult failure: an uncertain result

Now return to the customer who clicked Buy twice. The request handler might contain code shaped like this:

const order = await createOrder(cart);
return { orderId: order.id };

The order saves successfully, but the connection breaks before the response reaches the browser. The customer sees a timeout.

The database contains an order. The browser has no order ID. Clicking Buy again sends another request, and our handler creates another order.

We need a way to recognize that both requests represent the same purchase attempt. The browser can generate a request key before sending the first request and reuse it for retries:

First attempt:  request key checkout-7, cart A
Retry:          request key checkout-7, cart A
New purchase:   request key checkout-8, cart A

The server durably associates the key with the result. A retry with the same key and matching input returns the earlier order instead of creating another one. This makes the operation idempotent: repeating the request doesn’t repeat its intended effect.

There is still a race. Two copies of the request can both check for the key before either inserts it. A database uniqueness constraint and a transaction must coordinate the key and its order. An unlocked “check, then insert” leaves the problem unresolved.

Keep these outcomes separate:

  • Success response: the browser received confirmation.
  • Known rejection: the service rejected the purchase attempt.
  • Timeout: the browser doesn’t yet know the outcome.

The third outcome changes the API design. A lost reply doesn’t tell us whether the work happened. Amazon’s explanation of idempotent APIs develops this idea further.

Read an address and an HTTP exchange

We’ve described the request as GET /products/42. The browser also needs to know where to send it.

Consider https://photos.example:443/photos/42?size=small:

PieceExampleMeaning
SchemehttpsHow to communicate
Hostnamephotos.exampleName resolved through DNS
Port443The destination service endpoint on the host; 443 is the usual HTTPS default
Path/photos/42Resource or operation within the service
Querysize=smallAdditional request input

The hostname is a name, not a promise that one physical machine owns it. DNS can resolve it to addresses belonging to a shared proxy or a distributed service.

The destination port helps the receiving operating system deliver traffic to the right socket. DNS doesn’t normally select the path /photos/42 or produce the HTTP response.

Once the connection is established, an illustrative HTTP/1.1 exchange could look like this:

GET /photos/42?size=small HTTP/1.1
Host: photos.example
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json

{"id":42,"image_url":"https://images.example/photo-42-v1.jpg"}
  • The status code reports the outcome.
  • Headers describe the message, including its content type and caching instructions.
  • The body, when present, carries the representation.

The response could instead be a redirect: a 3xx status with a Location header. For example, 302 Found and Location: /photos/42 asks the client to make another request. A permanent redirect has different implications for future requests and caching than a temporary one.

You can inspect a response with curl -i https://example.com/. Add -L to follow redirects. Leave private credentials out of commands you plan to share.

Follow a request through the network

Our handler sees a request and eventually returns a result. Several layers make that exchange possible before the handler runs.

Build the journey one layer at a time

For a typical HTTPS request:

  1. DNS helps find an address for the hostname. A cached answer may avoid a fresh lookup.
  2. A transport connection carries the data between endpoints.
  3. TLS protects the exchange in transit and authenticates the server through certificates.
  4. HTTP gives the request and response their meaning.
  5. Application code validates the request and performs its work.

Each layer follows a protocol: rules that let the two sides interpret the exchange.

LayerFamiliar examplesJob
ApplicationHTTPDescribe requests and responses
SecurityTLSProtect communication
TransportTCP; QUIC over UDPCarry data between endpoints
NetworkIPAddress and route packets

HTTP/1.1 and HTTP/2 normally use TCP for HTTPS. HTTP/3 uses QUIC over UDP, with TLS security integrated into QUIC. Keeping those layers separate avoids the misleading shortcut that HTTP always means TCP.

Where does a proxy sit?

The address the browser reaches might belong to a program that forwards the request to our application. That intermediary is a proxy.

TypeActs on behalf ofExample
Forward proxyThe clientA company routes employee web traffic through a controlled exit
Reverse proxyThe serviceA public endpoint forwards requests to private application servers

Responses return through the corresponding connections. If the reverse proxy terminates the browser’s TLS connection, the next connection—from proxy to application—needs its own security decision. It doesn’t inherit protection merely because the first hop used HTTPS.

Give the waiting time a name

The customer is still looking at a loading indicator. To explain that wait, we need measurements with clear boundaries:

  • Network latency: delay moving data; specify one-way or round-trip.
  • Service time: time performing work at a component.
  • Queue time: time waiting for that work to start.
  • Response time: elapsed time the caller observes until a specified completion point.
  • Bandwidth: the link’s data-carrying capacity, usually in bits per second.

Some tools use “latency” for total request duration. Check what the tool measures before comparing its number with another dashboard.

A small response-time budget

Assume an existing connection, a small response, and sequential work:

StepIllustrative duration
Network travel across the request and response path40 ms
Waiting for an application worker20 ms
Application work10 ms
Database work30 ms
Total100 ms

These values are invented. Connection setup, streaming, and parallel work can change the accounting.

If queue time grows to 300 ms, optimizing 10 ms of application work won’t remove the main delay. The table helps us choose what to investigate.

A wider pipe does not shorten the road

A checkout response is small; its wait may come mostly from round trips and database work. A photo download has many more bytes to deliver.

Ignoring overhead, transferring 20 MB over a 10 megabit-per-second link takes about 16 seconds: 20 × 8 / 10. Increasing bandwidth can shorten that transfer. Reducing the physical distance can reduce network delay for both requests.

Open the browser’s Network panel and compare time waiting for the first byte with time downloading the body. Repeat the request and look for connection or cache reuse. The distinction is visible in ordinary tools.

The HTTP semantics and HTTP/3 specifications describe the protocol details.

What keeps a web server busy?

While one customer waits for a database read, another request arrives. Must it wait for the first request to finish?

That depends on how the server runs the work. The request handler is the application function. Server software also manages connections, parses requests, dispatches work, and sends responses.

TechniquePlain meaningUseful distinction
ConcurrencyKeep several tasks in progressTasks can alternate while waiting
ParallelismPerform work at the same instantRequires execution resources, such as multiple cores
Worker threads or processesSeveral workers handle workShared state needs coordination
Event loop with asynchronous I/OResume work when an operation is readyBlocking CPU work can still stall that loop

A blocking handler may spend time waiting for I/O. During that wait, the CPU could be doing useful work for another request. Concurrency makes that overlap possible; parallel execution requires resources that can actually run work at the same instant.

Walk through two concurrent requests

Assume one core and two workers. Each request needs 2 ms of CPU before a 20 ms database wait, then 1 ms of CPU afterward:

  • A prepares its query and waits.
  • B can use the CPU while A waits.
  • Each needs another short turn when its result arrives.

The waits overlap. The core still executes one thread’s instructions at an instant. More cores can permit CPU work in parallel, subject to the runtime and workload.

This explains why adding workers sometimes helps and sometimes disappoints:

  • I/O waits can leave capacity available for other requests.
  • CPU-heavy requests compete for the same cores.
  • More workers also consume memory and database connections.
  • Useful concurrency needs bounds; a growing thread count isn’t a capacity plan.

One process is not one tier

We can also separate responsibilities without changing the worker count:

  • Presentation gathers input and displays results.
  • Application logic checks permissions and applies business rules.
  • Storage keeps durable records.

These logical tiers may begin on one machine. Moving them onto different machines is a separate choice.

If workers share a counter, its read-increment-save sequence needs synchronization. A lock inside one process can coordinate its threads. Independent machines need shared authority, such as a database sequence or a durable allocation protocol.

Start an interview by narrowing the problem

We can now be more precise about an open-ended request such as “design a photo app.” Before selecting infrastructure, clarify what people should be able to do:

QuestionWhy it changes the design
Can anyone view a photo, or only approved followers?Changes authorization and caching
Do we need uploads and a profile page, or a personalized feed too?A feed adds a different query and ranking problem
Can users edit or delete photos?Changes freshness and removal requirements
How many uploads, reads, and retained days?Gives us capacity inputs
What must remain usable during a failure?Defines the availability goal

A first design might support uploads and profile pages while leaving recommendations and analytics outside the scope. Those boundaries give the discussion a useful size.

Clarifying questions can change the algorithm

Even “create an invitation code” leaves important behavior unspecified:

RequirementConsequence
Repeated requests for the same invitation return the same codeStore a stable association and define retry behavior
Each new invitation gets a different codeAllocate independently of identical display text
Codes expire after seven daysStore expiry and define what a later read returns
Users can choose a custom codeValidate it and atomically reject duplicates
We count every visitSeparate the lookup from the analytics event path

A hash function can’t decide what the product means by “the same invitation.” We need that answer before choosing the generator.

Likewise, viewing public image bytes, reading private metadata, editing a caption, and building a personalized feed may share records while needing different permissions, freshness, and traffic assumptions.

Breadth first, then depth

Start with the major responsibilities and how they connect. Then select a critical path and explain its data model, algorithm, failures, and limits.

For a store, catalog, inventory, checkout, and payment are useful responsibilities. They don’t have to become four separately deployed microservices. A modular application can keep them together initially.

A practical sequence is:

  1. Clarify the required user operations.
  2. Sketch responsibilities and one request path.
  3. Define its API and data.
  4. Make a first working design.
  5. Estimate demand and identify the first limit.
  6. Spend the remaining time on the part that matters most.

For checkout, the most revealing question might be what happens when the reply disappears after the order saves. We began with a small function; following one failure exposed persistence, retries, and coordination. The next chapter uses the same habit to reason about capacity.


Next: Estimate Capacity, Find Bottlenecks, and Set Useful SLOs.