Cutting Duplicate HTTP Calls in a curl-Driven Workflow
System DesignModel answerLast updated
Instrument an HTTP client to count and attribute its calls, detect wasteful repeats, reduce them safely, and prove the change is correct and stays fixed.
You own a client that talks to a REST API through curl, either shell scripts or a thin wrapper library. One user-facing workflow (for example: load a dashboard, read account balances, submit a transfer, then poll until it settles) feels slow, and the API owners say your traffic is heavier than it should be.
Describe how you would handle this end to end:
- Measure. Work out how many HTTP requests the workflow actually makes and which endpoints they hit, using curl and light instrumentation.
- Attribute. Decide what identifiers to attach and log so that every call can be tied to both a single request and the overall workflow run.
- Detect. Explain how you would spot redundant or repeated calls in the logs.
- Reduce. Describe the changes you would make to the client (batching, caching, debouncing or coalescing, or others) and say which situation each suits.
- Verify and protect. Explain how you would confirm outputs are unchanged, quantify the improvement, and stop the problem from returning.
State the assumptions you make. A strong answer treats writes, such as payments, more carefully than reads.
Hints
Hint 1
Start by defining the workflow boundaries and a numeric goal, then record one structured line per call (method, normalized route, status, latency) so you can group and count.
Hint 2
Use two kinds of identifiers: a unique one per call to join with server logs, and a shared one per workflow run to count everything that run did. Collapse IDs in URLs into templates before counting.
Hint 3
Match the fix to the pattern: concurrent identical reads need in-flight sharing, repeated reads need TTL or ETag caching, N+1 needs a bulk endpoint, tight polling needs backoff. Never dedupe writes unless an idempotency key makes it safe.
Hint 4
For proof, compare final outputs before and after, assert that the POST count and idempotency keys are unchanged, inject 5xx/429/timeouts, and add a request-budget check to CI.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: observe, attribute, fix, verify, guard
1. Scope and target
Before touching code I would pin down:
- Workflow boundaries. For example "open dashboard, read balances, create transfer, poll status until terminal." Fixed start and end points make counts comparable between runs.
- Client type. Shell script, CLI, or SDK. This decides where instrumentation lives.
- Read vs. write. Only idempotent GETs are cache candidates. A money-moving POST must never be silently merged or dropped unless an idempotency key makes retries safe.
- Freshness tolerance. Can a balance be 5 s stale? Can status polling be 2 s coarse?
- Server capabilities and limits. Rate limits (say 10 req/s per key), ETag support, bulk endpoints.
Then set a measurable goal, for example: "about 40 requests today, under 15 after, identical outputs, no p95 regression."
2. Baseline measurement
Per-call data in machine-readable form:
curl -sS -o /dev/null \
-H "X-Request-Id: $(uuidgen)" \
-H "X-Correlation-Id: $CORR_ID" \
-w '%{http_code} %{method} %{url_effective} %{time_total} %{num_redirects}\n' \
"$BASE/v1/wallets/$ID/balances" >> trace.log
curl -vor--trace-asciireveals hidden extras: redirects, connection reuse, auth round trips.- If you cannot edit every call site, run everything through a local intercepting proxy (e.g. mitmproxy via
HTTPS_PROXY) and capture all traffic.
Aggregate with normalized routes so IDs collapse to templates:
awk '{print $2, $3}' trace.log | sed -E 's/[0-9a-f-]{36}/:id/g' | sort | uniq -c | sort -rn
This gives total calls, distinct endpoints and repeat counts. A line like 12 GET /v1/wallets/:id/balances is the first suspect.
3. Identifiers and structured logs
- Request ID: unique per HTTP call. Lets you join one client line to the gateway and server logs.
- Correlation ID: one per workflow run, sent on every call (or as W3C
traceparentif using OpenTelemetry). Lets you answer "how many calls did this run make?" with a single group-by.
Log one JSON line per call:
{"corr_id":"wf-7f3a","req_id":"9c1e","method":"GET","route":"/v1/wallets/:id/balances",
"status":200,"ms":84,"caller":"refresh_balances","attempt":1,"cache":"miss"}
caller and attempt separate logic bugs (same function twice) from retries and from fan-out across components.
4. Detecting redundancy
Group by correlation ID and look for:
| Pattern | Signal | Likely cause |
|---|---|---|
| Exact duplicates | same method, route, query, body hash within a short window | two components fetching the same thing |
| N+1 | one list call then k item calls | no batch or include parameter |
| Tight polling | same GET every ~1 s with no backoff | fixed-interval loop |
| Retry storms | attempt > 1 on 4xx | retrying non-retryable errors |
| Hidden extras | 301/302, token refresh per call, new TLS each time | config issues |
A simple detector hashes (method, route, query, body) per correlation ID and reports keys with count > 1, plus a hash of the response. Identical responses prove the repeat was wasted.
5. Fixes by pattern
- In-flight dedupe (singleflight). Concurrent identical GETs share one pending result.
- Caching. Short TTL keyed on the normalized request. Prefer conditional requests (
If-None-Match, 304) so correctness does not rest on a guessed TTL. Invalidate related keys after writes, e.g. evict balances after a transfer. - Batching. Replace N+1 with
GET /items?ids=a,b,cor a bulk endpoint, chunked to the server maximum. - Debounce/coalesce. Collapse bursts of refresh triggers into one call per window. Replace fixed polling with capped exponential backoff (1, 2, 4, 8 s), or use webhooks or long polling if offered.
- Retry policy. Retry only on 5xx, 429 and timeouts, with jitter, honoring
Retry-After. Always send an idempotency key on POSTs so a retry cannot double-execute. - Connection reuse. One session with keep-alive, avoiding repeated TLS handshakes.
Sketch of a wrapper:
class Client:
def __init__(self, session, ttl=5.0):
self.s, self.ttl = session, ttl
self.cache, self.inflight = {}, {}
self.lock = threading.Lock()
def get(self, path, corr_id):
with self.lock:
hit = self.cache.get(path)
if hit and time.monotonic() - hit[0] < self.ttl:
log(corr_id, path, cache="hit")
return hit[1]
fut = self.inflight.get(path)
owner = fut is None
if owner:
fut = self.inflight[path] = Future()
if not owner:
return fut.result()
try:
r = self.s.get(BASE + path, headers=ids(corr_id))
r.raise_for_status()
data = r.json()
with self.lock:
self.cache[path] = (time.monotonic(), data)
fut.set_result(data)
return data
except Exception as e:
fut.set_exception(e) # failures are never cached
raise
finally:
with self.lock:
self.inflight.pop(path, None)
def invalidate(self, prefix):
with self.lock:
for k in [k for k in self.cache if k.startswith(prefix)]:
del self.cache[k]
Key properties: failures are not cached, the lock protects shared state, and writes call invalidate.
6. Verifying correctness
- Golden comparison. Run the workflow before and after against the same sandbox state and diff final outputs.
- Write invariants. POST count unchanged, every POST has a unique idempotency key, and a forced retry yields exactly one server-side transfer.
- Staleness test. A read after a write must reflect it, which exercises invalidation.
- Fault injection. Use a mock server or proxy to return 500, 429 and timeouts. Confirm retry behavior and that a failed in-flight call does not poison the cache.
7. Measuring improvement
Compare 20+ runs before and after, using medians and p95:
- Requests per workflow, total and per route (e.g. 40 to 12).
- Bytes, new TLS connections, redirects, 429 count.
- End-to-end latency p50/p95. Batching can lengthen a single call, so judge the total.
- Cache hit rate and 304 ratio.
8. Preventing regressions
- A CI test that runs the workflow against a mock server and fails if request count exceeds a budget (for example 15, per route as well).
- A production counter such as
http_client_requests_total{route,caller}plus a "requests per workflow" histogram, with alerts on a step change after deploys. - A lint or log check that flags duplicate keys within one correlation ID.
Common mistakes
- Caching or deduplicating non-idempotent writes.
- Counting raw URLs instead of normalized routes, hiding repeats.
- Picking a TTL without a freshness requirement, or forgetting invalidation on writes.
- Caching error responses.
- Measuring once instead of reporting distributions.
- Retrying everything, which turns a small fault into a traffic spike.
Trade-offs
Caching trades freshness for fewer calls (ETags reduce that risk). Batching reduces count but raises payload size and partial-failure complexity. Debouncing adds latency up to the window. Pick the least invasive fix that meets the target and keep the budget test to hold the gain.