TweakCode
Design Method lessons

Interfaces · Stage 2 of 3

Internal Interfaces & Shared State

Define a hot-path check, the state it updates atomically, and its failure policy

Foundations

In the first lesson, the interface faced users over HTTP. Now, what if the caller is another component, the call runs before every request, and two copies of the caller may race on the same state?

An internal interface still needs a contract: its inputs, its result, and what callers do with each result. When many processes share state, the read and the update must be one atomic operation in the shared store, or two callers can both act on a value only one should have seen. And every dependency needs a declared down policy: fail open and continue, or fail closed and refuse.

Take a quota check, allow(key), called by several front-end processes before each request. It reads and decrements a counter for key in a shared store. If two processes read 1 at once and each decrements, both proceed though only one should; one atomic decrement-if-positive prevents that. If the store is down, the contract says which way to fail.

if allowedFront end 1allow(key)?Front end 2allow(key)?Shared storeatomic checkService
Both front ends ask the same store at once. One atomic check-and-decrement means only one gets the last unit, and a declared policy covers the store being down.
  • Requirements

    Estimates and APIs start from an agreed list of what the system must do.

    Open lesson

Case Scenario

The design brief

Write the rate limiter API

Every API request asks a limiter whether this user may proceed. The limiter allows 100 requests per minute.

To see how an internal check needs a contract, consider an API rate limiter, the kind GitHub and Stripe place in front of their public APIs: every request asks whether this caller may proceed, here under a limit of 100 per minute. The gateway calls allow(key), a denied caller gets 429 with Retry-After, and two gateways must never spend the same last token.

Every API request needs a fast yes-or-no decision before expensive work begins. Two simultaneous requests from the same user must not both spend the last allowance, and an unavailable limiter must not accidentally become a full API outage. For a 100-requests-per-minute user, the check must be atomic, add less than one millisecond, and have an explicit down-state policy.

Pro

The rest of this is on Pro

The idea above is free. The walkthrough, the cost, and the practice are on Pro.