Design a Cost-Reduction Gateway for Metered Upstream APIs
System DesignModel answerLast updated
Design a shared proxy that sits between internal microservices and pay-per-call APIs, cutting spend through caching, request collapsing, batching, and budget enforcement.
Background
Your organization runs dozens of microservices, and a meaningful slice of the monthly infrastructure bill comes from calls to metered API endpoints — third-party data providers, payment processors, enrichment services, and internal platforms that chargeback per request. As the number of services grows, so does duplicate and redundant outbound traffic.
Your task is to design a shared gateway layer that intercepts those outbound calls and reduces how many actually reach the upstream, without changing what the calling service receives. For every technique you propose, explain where the saving comes from, when it is safe to apply, and what could go wrong.
Assume endpoints charge per request, that traffic is a mix of read-style lookups and writes that must never be sent twice, and that the gateway can be introduced gradually. No concrete scale or pricing is provided — state your own assumptions whenever you need numbers.
Constraints
- A service must never receive someone else's data, a response that is too stale for its use case, or the side-effect of a duplicated write.
- The gateway itself adds a network hop and a processing step; its latency impact and its own availability are part of the design.
- The gateway costs money to operate; that cost must be smaller than the savings it generates.
Useful questions to consider (clarifications)
- What makes up the bill: per-call charges, data egress, or both?
- Which endpoints are read-only, and what freshness do callers actually need?
- Do any upstreams offer batch endpoints or volume pricing tiers?
- Which services and which endpoints account for the majority of spend today?
- Can services change their code to point at the gateway, or must interception be transparent?
Part 1 — Requirements and placement
Define what the gateway must and must not do. Decide where it runs — a centralized gateway process, a sidecar next to each service, or an in-process client library — and justify that choice. Sketch the main components and walk through the lifecycle of one request.
Cover:
- Functional and non-functional requirements, including latency and availability targets for the gateway itself
- Placement decision with trade-offs
- Component diagram (described in prose or ASCII)
- How existing services adopt it without a big-bang migration
Part 2 — Mechanisms that reduce cost
Propose the concrete techniques the gateway uses to reduce billable calls or the cost per call. For each one, state when it is safe to apply.
Cover:
- Response caching: what is cacheable, how cache keys are constructed, and how freshness is managed
- Collapsing multiple in-flight identical requests into one upstream call
- Batching separate requests from different callers into a single upstream call
- Per-service quotas, rate limits, and spending budgets
- Routing to cheaper providers, pricing tiers, or alternative request shapes
Part 3 — Correctness, failures, and cost visibility
Explain how you avoid the three correctness risks from the constraints section: data leakage across callers, serving stale data, and double-charging writes on retry. Then cover what happens when things break, and how you prove the gateway is actually saving money.
Cover:
- Safe retries and idempotency handling for write-style requests
- Fail-open vs. fail-closed behavior for gateway failures, cache failures, and upstream failures
- Per-service cost metering and attribution
- Metrics and alerts that demonstrate savings and catch regressions
Hints
Hint 1
Start with measurement, not mechanism. Before designing any saving technique, establish how you'd know which services call which endpoints and how often — that shapes every other decision.
Hint 2
Think carefully about what makes a cache key safe. The same request payload from two different services, or two different tenants, may not be interchangeable. Leaking data between callers is worse than making an extra billable call.
Hint 3
Writes need a different contract than reads everywhere in the design — retries, caching, request collapsing, and failure policy all need separate treatment for anything that mutates state.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Requirements and Placement
Requirements
Functional: intercept outbound calls to metered endpoints; cache eligible responses; collapse duplicate in-flight requests; batch requests where the upstream supports it; enforce per-service quotas and budgets; route to cheaper alternatives when available; emit per-service cost attribution.
Non-functional: add no more than 5–10 ms of p99 latency on a cache hit, 20–30 ms on a cache miss (co-located with services); target 99.9% availability — a gateway outage must not take down the services that depend on it; operate at a cost well below the savings, which a simple model can bound (e.g., if the top 10 endpoints cost $50k/month and a 40% cache hit rate is realistic, the break-even gateway budget is ~$20k/month before any batching or collapsing gains).
Placement Decision
Three options exist: a centralized gateway (one or a small fleet of processes all traffic routes through), a sidecar per service, or an in-process library.
A centralized gateway wins here because it provides a global view of in-flight requests across all services — which is necessary for request collapsing and accurate spend aggregation. The trade-off is a single point of failure and a shared blast radius; mitigate that with horizontal scaling, a circuit breaker on the gateway path, and a fail-open bypass so services can reach upstreams directly if the gateway is unavailable.
Sidecars offer better fault isolation but can't collapse requests from different services. A library can't be rolled out without code changes to every service. A centralized gateway can be introduced transparently via a DNS alias or a service mesh routing rule, which supports gradual adoption.
Components and Request Path
Service A ──┐
Service B ──┼──► [Gateway fleet] ──► [Upstream API]
Service C ──┘ │
[Cache (Redis)]
[Budget store]
[Metrics sink]
Request lifecycle: the gateway receives the outgoing call, checks the budget for that service, constructs a cache key, looks up the cache. On a hit it returns immediately. On a miss it checks whether an identical in-flight request already exists (collapsing); if not, it forwards to the upstream, stores the response in cache if eligible, records the cost, and returns the response. Writes skip the cache entirely and go directly to the upstream after an idempotency check.
Part 2 — Cost-Reduction Mechanisms
Response Caching
Cacheable endpoints are read-only with a known or inferrable TTL. The cache key must include: the endpoint identifier, the full request parameters, and the calling service's tenant or auth scope — never just the request payload alone, or you risk serving one tenant's data to another.
Freshness is controlled per endpoint, not globally. Some endpoints (e.g., a currency conversion rate) tolerate 60-second TTLs; others (e.g., a fraud score for a specific transaction) should not be cached at all. Maintain an allow-list of cacheable endpoints with their TTLs, defaulting to non-cacheable for anything not explicitly listed. Cache-Control headers from the upstream can inform TTLs but should be treated as a ceiling, not a floor.
Request Collapsing
When two services issue identical in-flight requests (same endpoint, same parameters, same tenant scope) within a short window (e.g., 50 ms), hold the second request and fan the single upstream response back to both callers. This is safe only for reads. The saving scales with how "bursty" the traffic is — a deployment event that causes 20 services to revalidate the same config endpoint simultaneously is a good example of where collapsing matters.
Batching
Some upstreams accept a list of IDs in one call instead of one call per ID. The gateway can buffer individual requests for a short window (5–20 ms, tunable) and dispatch a single batch request. Return each item to the appropriate caller. Risk: the batching window adds latency for the first callers in the batch; make the window configurable and allow callers to opt out with a header.
Quotas and Budgets
Each service gets a configurable rate limit (requests per second) and a monthly spend budget. The budget store is a lightweight counter updated on each forwarded request with the known per-call price. When a service approaches its budget, the gateway can throttle it, emit an alert, or return a synthetic error — the policy is configurable per service. This creates accountability and catches runaway callers early.
Provider Routing
Where multiple providers offer equivalent responses (e.g., two geocoding APIs), route based on current pricing, response time, or remaining free-tier quota. A/B test new providers at low traffic percentages before shifting the default. Some upstreams also offer a cheaper "cached" or "lite" tier that returns slightly less data; route to it when the caller only needs the fields in that tier.
Part 3 — Correctness, Failures, and Visibility
Safe Retries for Writes
Classify every registered endpoint as read or write at configuration time. Writes bypass caching and collapsing entirely. For retries, require or generate an idempotency key: if the upstream supports idempotency keys (most payment and mutation APIs do), the gateway attaches one on the first attempt and reuses it on retries. If it doesn't, the gateway retries only on network-level failures (timeouts, connection refused) where no response was received — never on a 5xx that may have been applied.
Failure Policies
| Component fails | Policy |
|---|---|
| Cache (Redis) unavailable | Fail open: bypass cache, forward directly. Cost rises temporarily; no correctness issue. |
| Gateway process unavailable | Fail open: DNS/service-mesh fallback routes directly to upstream. Budget tracking is lost during this window. |
| Upstream unavailable | Fail closed by default (return error to caller). For endpoints where a slightly stale response is acceptable, serve the last cached value with an Age header and a background revalidation. Configurable per endpoint. |
| Budget exceeded | Configurable: throttle (429) or allow with alert. Never silently drop. |
Cost Attribution and Metrics
Each forwarded call is tagged with: service name, endpoint, response source (cache/upstream/batch), and the known per-call cost. Emit these to a metrics system. Build dashboards showing:
- Total spend per service per day, compared to budget
- Cache hit rate and cost avoided (hits × per-call price)
- Collapsing and batching savings (calls avoided × per-call price)
- Gateway overhead cost (compute + memory) subtracted to give net savings
Alert on: cache hit rate dropping more than 10 points week-over-week (possible TTL misconfiguration or new uncacheable traffic); any service exceeding 80% of its monthly budget before month-end; upstream error rate exceeding a threshold (possible provider issue or quota exhaustion on their side).
Common Mistakes to Avoid
- Using only the request body as a cache key without scoping by tenant — this is a data leakage bug, not a performance bug.
- Retrying writes unconditionally on 5xx — double charges are often worse than a failed transaction.
- Setting a global TTL instead of per-endpoint TTLs — caching a fraud score for 60 seconds is a correctness failure.
- Skipping the gateway cost in the ROI calculation — a gateway that costs more than it saves is just a slow proxy.