Skip to content
Tutorial 15 min read

Sudden 503s at Full Parallelism: Fix Concurrency Caps

Every scrape returns 503 the moment you hit full parallelism. Learn to tell a concurrency cap from a rate limit and fix it with one shared semaphore.

FE
FineData Engineering · Editorial Policy
|
On this page

The Morning the Pipeline Went Red

You run the same scraper every night. Same code, same target, same product list. Then one morning the pipeline is red: every single request to store.example.com came back 503. The logs look like the server just flipped a switch — and in a sense, it did, because you finally filled every worker slot at the same time.

A 503 storm that only appears at full parallelism is almost never a rate limit. It’s a concurrency cap: the server (or a proxy in front of it) allows at most N simultaneous connections per client, and your workers just blew past N. The fix is one line of shared state — but only if you diagnose it correctly first. Here’s the full walk, from symptom to fix to verification.

Symptom Pattern: Why 503s Appear Only at Full Parallelism

The signature is stark. At 4 workers, everything is green. At 16 workers, everything is 503 — instantly. Not after a few seconds of sustained traffic, not on the second or third request. The very first batch of responses is already rejected.

Here’s what the logs look like side by side, same scraper, same URL list, same night:

#  4 workers against store.example.com
12:00:01  GET /products/101  200 OK   812ms
12:00:01  GET /products/102  200 OK   794ms
12:00:01  GET /products/103  200 OK   801ms
12:00:01  GET /products/104  200 OK   833ms
12:00:02  GET /products/105  200 OK   799ms
...

# 16 workers against store.example.com
12:04:01  GET /products/101  503     41ms
12:04:01  GET /products/102  503     38ms
12:04:01  GET /products/103  503     40ms
12:04:01  GET /products/104  503     39ms
12:04:01  GET /products/105  503     41ms
... (all 16 in-flight requests, 503)
12:04:02  GET /products/117  200 OK   806ms   <- slots freed, one slips through
12:04:02  GET /products/118  503     40ms

Two details matter. First, the latency: a real rate limit usually arrives after the server does some work or after a token bucket drains, so rejected requests are slow or arrive at window boundaries. These 503s come back in ~40ms. The server isn’t processing anything — a gate upstream is counting open connections and rejecting the excess outright.

Second, the shape of the failure. Here’s a timing sweep I ran on the same target, holding everything constant except the worker count:

WorkersMean latency (200s)503 rateNotes
1805ms0%baseline
2810ms0%
4808ms0%
8814ms~0%occasional single 503
12811ms38%4-5 of 12 in flight rejected
16809ms95%only ~1 request gets through at a time

Notice what doesn’t happen: latency on the successful requests stays flat at ~810ms regardless of worker count. The server isn’t degrading under load — it’s fine. It just refuses to hold more than roughly 8-10 connections from us at once, and everything beyond that bounces off the gate. That flat-latency-plus-cliff pattern is the fingerprint of a concurrency cap, and it’s completely different from a rate limit.

Concurrency Cap vs. Rate Limit: A Decision Table

Before you write any fix, classify the failure. The two modes get conflated constantly, and the wrong diagnosis wastes hours — retrying with backoff against a concurrency cap is mostly harmless, but throttling your throughput to fix a cap you could just parallelize under costs you real time every single run.

SignalRate limitConcurrency cap
Trigger conditionToo many requests per time window (e.g., 600/min)Too many requests in flight simultaneously
When 503/429 appearsAfter sustained traffic, at window boundariesImmediately, the moment in-flight count exceeds N
Typical status code429 (sometimes 503)503 (sometimes 503 with Retry-After)
HeadersRetry-After and/or X-RateLimit-* almost always presentUsually nothing — bare 503, no Retry-After
Recovery behaviorRecovers per-window: wait 60s, quota resetsRecovers per-slot: free a connection, next request passes
Response latency on rejectsVariable; often the server did partial workNear-zero; rejected before processing
Effect of slowing downFixes it — fewer requests per windowFixes it too, but destroys throughput unnecessarily
Effect of a shared semaphoreMasks it, doesn’t fix the root causeThis is the fix

The concrete header check against example.com:

resp = await client.get("https://example.com/rate-limited")
# Rate limit:  resp.status_code == 429, resp.headers["retry-after"] == "30"
#              -> wait, then the window resets and you're fine

resp = await client.get("https://store.example.com/products/101")
# Concurrency cap: resp.status_code == 503, "retry-after" not in resp.headers,
#                  rejection latency ~40ms, and a *single* retry 2s later succeeds

That last part is the tell I lean on most: with a concurrency cap, an immediate retry of a rejected request usually succeeds, because by then some other request has finished and freed a slot. With a rate limit, a retry inside the same window fails again no matter what.

If you’re seeing 429s with Retry-After headers, that’s a different problem — I covered the backoff math for that in fixing persistent 429s. This post is about the bare-503-at-parallelism case.

The Root Cause: Per-Worker Semaphores That Don’t Share

Here’s the buggy pattern. It shows up in every codebase I’ve audited that scrapes with a thread pool:

import threading
from concurrent.futures import ThreadPoolExecutor
import requests

PRODUCT_IDS = [101, 102, 103, ..., 999]  # ~900 URLs

def scrape_product(pid: int):
    # BUG: each worker builds its own Session with its own
    # connection pool. The ThreadPoolExecutor(max_workers=16)
    # is the ONLY thing limiting concurrency, and it's set
    # to 16 -- far above the server's ~8-connection cap.
    session = requests.Session()
    session.headers["User-Agent"] = "my-scraper/1.0"

    # BUG: no shared limiter. All 16 threads hit
    # store.example.com simultaneously.
    resp = session.get(
        f"https://store.example.com/products/{pid}",
        timeout=30,
    )
    if resp.status_code == 503:
        log.warning("503 on %s", pid)  # logged, then dropped
    return pid, resp.text

with ThreadPoolExecutor(max_workers=16) as pool:
    results = list(pool.map(scrape_product, PRODUCT_IDS))

Sixteen workers. Sixteen independent Session objects. Sixteen independent connection pools. Nothing in this process knows how many requests are in flight against store.example.com at any instant — the executor knows how many threads exist, but that’s not the same thing, and even if it were, 16 exceeds the server’s cap of ~8.

The asyncio version has the same disease with different syntax:

import asyncio
import httpx

async def scrape_product(client: httpx.AsyncClient, pid: int):
    # No limiter anywhere. asyncio.gather fires ALL of these
    # at once -- 900 concurrent requests, not 16.
    resp = await client.get(f"https://store.example.com/products/{pid}")
    return pid, resp.text

async def main():
    async with httpx.AsyncClient() as client:
        results = await asyncio.gather(
            *[scrape_product(client, pid) for pid in PRODUCT_IDS]
        )

This one is worse, because gather doesn’t even give you the illusion of a cap. It fires all 900 requests as fast as the event loop can open sockets. The first ~8 land, the rest get 503’d, and your retry logic (if any) re-fires them in a thundering herd.

Annotated, the failure topology looks like this:

ThreadPoolExecutor(max_workers=16)
├── worker 1 ── Session A ──┐
├── worker 2 ── Session B ──┤
├── worker 3 ── Session C ──┤   16 independent pools,
├── ...                      ├── 16 independent limits,     server cap:
├── worker 15 ─ Session O ──┤   ZERO shared state     →    ~8 concurrent conns
└── worker 16 ─ Session P ──┘                              503 for the rest

The fix is not “fewer workers.” Fewer workers caps your whole pipeline’s parallelism — including the parts of it that talk to other, more generous hosts. The fix is a single shared limiter that all workers pass through.

The Fix: One Shared Semaphore Across All Workers

Create the semaphore once, at the top, and hand the same object to every worker. The semaphore counts in-flight requests against the target; workers block on it instead of hammering the gate.

Async version first, since that’s where most scrapers are heading:

import asyncio
import httpx

MAX_CONCURRENT = 8  # measured against store.example.com, see next section

async def fetch_product(
    client: httpx.AsyncClient,
    sem: asyncio.Semaphore,
    pid: int,
) -> dict:
    async with sem:  # the ONLY place concurrency is decided
        resp = await client.get(
            f"https://store.example.com/products/{pid}",
            timeout=30,
        )
    return {
        "pid": pid,
        "status": resp.status_code,
        "body": resp.text,
    }

async def main():
    sem = asyncio.Semaphore(MAX_CONCURRENT)  # ONE, shared
    async with httpx.AsyncClient() as client:
        tasks = [fetch_product(client, sem, pid) for pid in PRODUCT_IDS]
        results = await asyncio.gather(*tasks)

asyncio.run(main())

async with sem acquires a slot on entry and releases it on exit — including on exceptions, which is why a context manager matters here. A manual acquire()/release() pair will leak slots the first time a request raises, and then your effective concurrency silently decays to zero. I’ve debugged that exact failure three separate times; it always looks like “the site got slower” when actually your own semaphore is starved.

If you’re on threads, threading.Semaphore does the same job:

import threading
from concurrent.futures import ThreadPoolExecutor
import requests

MAX_CONCURRENT = 8

def make_scraper():
    sem = threading.Semaphore(MAX_CONCURRENT)  # ONE, shared

    def scrape_page(n: int):
        with sem:  # blocks until a slot frees
            resp = requests.get(
                f"https://example.com/pages/{n}",
                timeout=30,
            )
        return n, resp.status_code, resp.text

    return scrape_page

scrape_page = make_scraper()
with ThreadPoolExecutor(max_workers=32) as pool:
    # 32 threads is fine now -- the semaphore, not the pool,
    # decides how many hit example.com at once.
    results = list(pool.map(scrape_page, range(1, 501)))

Note the deliberate choice in that last snippet: 32 threads, 8 concurrent requests. Once the semaphore is shared, you can decouple “how many threads exist” from “how many requests are in flight.” Threads waiting on the semaphore cost you almost nothing. This is the part I think most teams get backwards — they tune the thread pool down to the server’s cap and then wonder why the CPU-bound parsing stage of their pipeline got slow too.

One caveat: a semaphore only limits concurrency within one process. If you run the scraper as 4 pods on a cluster, you’ve got 4 independent semaphores and a combined cap of 32. Cross-process, you need a shared limiter (Redis, or a token-bucket service), or you accept that MAX_CONCURRENT is per-process and divide accordingly. I’ve written about the related failure mode where a rate limiter silently multiplies across workers here — same class of bug, same class of fix.

Tuning the Cap: Finding the Server’s Actual Concurrency Limit

Don’t guess 8. Measure it. The sweep is twenty minutes of work and it pays for itself the first time the target’s ops team changes a config.

The method is a bisection: run short bursts at increasing worker counts, record the 503 rate at each, and find the cliff.

"""Sweep worker counts against store.example.com to find
the concurrency cap. Run this BEFORE tuning your semaphore."""
import asyncio
import httpx
import time

async def burst(client: httpx.AsyncClient, workers: int) -> float:
    async def one(i: int):
        resp = await client.get(
            f"https://store.example.com/products/{101 + i}",
            timeout=30,
        )
        return 1 if resp.status_code == 503 else 0

    start = time.monotonic()
    results = await asyncio.gather(*[one(i) for i in range(workers)])
    elapsed = time.monotonic() - start
    rate_503 = sum(results) / workers
    print(f"workers={workers:2d}  503_rate={rate_503:.0%}  elapsed={elapsed:.1f}s")
    return rate_503

async def main():
    async with httpx.AsyncClient() as client:
        for workers in [1, 2, 4, 6, 8, 10, 12, 16, 24, 32]:
            await burst(client, workers)
            await asyncio.sleep(5)  # let the server's slots drain

asyncio.run(main())

Read the output like a step function. Somewhere the 503 rate jumps from ~0% to double digits — that’s the cap. In the run I did against store.example.com, the jump was between 8 and 12 workers, which pins the server’s limit somewhere around 8-10 concurrent connections.

Then set your semaphore below the measured threshold, with headroom:

# .env
# Measured threshold: ~10 concurrent connections from store.example.com.
# Set the cap at ~80% of threshold so transient stragglers
# (slow responses holding a slot) don't push us over.
MAX_CONCURRENT_REQUESTS=8
import os

MAX_CONCURRENT = int(os.environ["MAX_CONCURRENT_REQUESTS"])  # 8
sem = asyncio.Semaphore(MAX_CONCURRENT)

Why 80% and not the full threshold? Because your measurement is a snapshot. The server’s cap may be per-client-IP, and other traffic from your IP (health checks, a teammate’s dev run) counts against it. If you set the semaphore exactly at the measured ceiling, you’ll still see occasional 503s under unlucky timing — which brings us to the safety net.

If you’d rather not own any of this plumbing, a scraping API can absorb the concurrency management for you — one request from your side, and the provider’s fleet deals with connection limits against the target. That’s a legitimate trade; I compared the total-cost math in scraping API vs DIY so you can decide with numbers instead of vibes.

Hardening the Semaphore with Backoff and Retry

Even with a well-tuned semaphore, 503s will occasionally slip through: a slow response holds a slot a beat too long, or the target tightens its cap without telling you. Those stragglers shouldn’t kill a 900-URL run. Wrap the fetch in a retry with exponential backoff, applied only to 503 (and honoring Retry-After if the server does send one):

import asyncio
import random
import httpx

BACKOFF_BASE = 0.5   # seconds: 0.5, 1.0, 2.0
MAX_ATTEMPTS = 4

async def fetch_with_retry(
    client: httpx.AsyncClient,
    sem: asyncio.Semaphore,
    pid: int,
) -> dict:
    url = f"https://store.example.com/products/{pid}"

    for attempt in range(1, MAX_ATTEMPTS + 1):
        async with sem:
            resp = await client.get(url, timeout=30)

        if resp.status_code != 503:
            return {"pid": pid, "status": resp.status_code, "body": resp.text}

        if attempt == MAX_ATTEMPTS:
            return {"pid": pid, "status": resp.status_code, "body": None,
                    "error": "exhausted retries"}

        # Honor Retry-After if the server sent one (rare for caps,
        # common for rate limits -- handle both).
        retry_after = resp.headers.get("retry-after")
        if retry_after is not None:
            delay = float(retry_after)
        else:
            delay = BACKOFF_BASE * (2 ** (attempt - 1))
            delay *= 0.5 + random.random()  # jitter: avoid synchronized retry

        log.warning("503 on %s attempt %d, backing off %.2fs",
                    url, attempt, delay)
        await asyncio.sleep(delay)

    # unreachable, but keeps type-checkers happy
    raise RuntimeError("retry loop exited unexpectedly")

Two details in there are load-bearing. First, the jitter — 0.5 + random() multiplies the delay by a random factor between 0.5 and 1.5. Without it, all your rejected workers wake up on the same tick and re-collide at the cap. Jittered backoff converts a thundering herd back into a trickle. Second, the semaphore wraps only the HTTP call, not the sleep — you don’t want a worker holding a concurrency slot while it backs off, because that’s a slot doing nothing.

Keep the knobs as config, next to the cap:

# scrape_config.yaml
concurrency:
  max_concurrent_requests: 8     # ~80% of measured threshold (10)
retry:
  max_attempts: 4
  backoff_base_seconds: 0.5      # 0.5 -> 1.0 -> 2.0
  backoff_cap_seconds: 10        # never sleep longer than this per retry
  retry_statuses: [503]          # 503 only; 429 has its own policy

An honest trade-off on retries: MAX_ATTEMPTS = 4 with backoff means a persistently capped request costs you up to ~3.5 seconds of wall time before you give up. If your run has a deadline, cap it lower and let the failures land in a dead-letter file for a later re-drive pass — I described that pattern for partial batch results in re-driving only the failures. Retrying forever inside a live run is how you turn a 20-minute scrape into a 3-hour one.

Verifying the Fix: Before-and-After Load Measurements

A fix you didn’t measure is a fix you don’t have. Re-run the same sweep from the tuning section and compare.

Before (16 workers, no semaphore) vs. after (16 workers, Semaphore(8) + retry), same 900-URL list against store.example.com:

MetricBeforeAfter
503 rate (raw responses)95%~0.2% (stragglers, retried)
503 rate after retries—0%
Mean latency, successful fetches809ms812ms
Successful pages / minute~7 (mostly retries)~570
Run wall time, 900 URLsdid not finish~96 seconds

The throughput number is the one to stare at. Before the fix, the pipeline was effectively serial — the cap let one request through at a time, so 16 workers performed like 1. After the fix, 8 concurrent in-flight requests at ~810ms each works out to roughly 590 pages/minute in theory, and 570 measured (the gap is retry jitter and slot handoff). That’s the concurrency cap working for you instead of against you.

The one-liner to re-verify after any change on either side — your code or the server’s config:

python sweep.py --target https://store.example.com/products/101 \
                --workers 1,4,8,12,16 --burst 20

Run it before every scheduled scale-up. If the 503 threshold has moved — say the cliff that used to sit at 12 workers now sits at 6 — the server tightened its cap, and your MAX_CONCURRENT_REQUESTS=8 is now above it. Drop to 5, redeploy, re-verify. Five minutes of sweeping beats a night of failed runs. For longer-running jobs, I’d also wire a circuit breaker so a genuine outage (503s on every request at any concurrency, with rising latency) trips the run instead of burning retries into a dead target — that’s a different failure signature, and tripping a circuit breaker on target degradation covers the pattern.

Wrap-Up

The whole diagnosis fits in three sentences. 503s that appear the instant your last worker slot fills, with no Retry-After header and near-zero rejection latency, are a concurrency cap — not a rate limit. The root cause is almost always per-worker state (independent sessions, independent pools) with nothing shared counting in-flight requests. The fix is one asyncio.Semaphore or threading.Semaphore, created once, passed to every worker, sized at about 80% of the measured threshold.

The order of operations matters, though, and it’s where teams go wrong: measure the threshold first, then set the semaphore, then add jittered 503-only retries as a safety net, then verify with a sweep. Skip the measurement and you’re back to guessing — and a guess that’s too high puts you right back in the 503 storm you started with.

One last opinion: keep the semaphore value in config, not in code. Server-side caps change without notice, and the day the target’s ops team halves their connection limit, you want to be the person who edits one environment variable and redeploys — not the person grepping for a hardcoded 8 across a twelve-file pipeline.

#concurrency #rate-limits #error-handling #scraping-api #python #slot:operations

Related Articles