DEV Community

Cover image for The Best Café in Town Turns People Away. Your System Should Too
Shubhra Pokhariya for The Third Cup

Posted on Originally published at shubhra.dev AI-assisted

The Best Café in Town Turns People Away. Your System Should Too

API error design through a café analogy

Two cafés, both completely full at 8:15 on a Monday. Both are about to turn away the next person through the door. (Both imaginary. Probably.)

At the first café, you join the line. Nobody says anything. After four minutes you notice the barista has been looking straight through you since you walked in. Somewhere around minute five you work out that you are not getting a coffee.

At the second café, someone at the door says: "We're full for about ten minutes. The place next door has seats, and we'll be here when you're back."

Same capacity. Same number of people turned away. One café gets a thank-you and a regular. The other gets a one-star review and a story told at dinner.

Queue limits, load shedding and utilisation curves help decide when to say no. This post is about what the no itself looks like. In an API, the refusal is part of your interface. Client libraries, proxies, dashboards and a tired human at 3 a.m. all have to read it.

Five bad ways to say no

Five bad ways to say no: slow (the no takes as long as a yes), silent (no response), vague (a 500 hides the reason), lying (says 200 OK, means no), too-late (work starts before capacity is checked)

The Slow No. The server holds the connection for thirty seconds, tries everything, then gives up. The caller waited the whole time. A no that costs as much as a yes saves you nothing.

The Silent No. The connection just drops. Now the client has an impossible question: did the server start my request or not? Without an answer it can't know whether retrying is safe.

The Vague No. A 500 Internal Server Error with the body "Something went wrong." It's the barista saying "sorry, something happened" and going back to wiping the counter. A 500 signals an unexpected server-side condition. Busy is not necessarily broken, and callers deserve to know the difference.

The Lying No. A 200 OK with {"ok": false} in the body. Most HTTP-aware tooling treats a 2xx as success unless someone has configured it to look inside the body. Your status-based error metrics can sit at zero while customers go unserved. The dashboard stays very calm.

The Too-Late No. It takes the payment, then says sorry. Don't do anything irreversible, like charging a card, sending an email or committing a write, until the request has passed admission and your own validation. An admission refusal shouldn't start a payment or leave a write halfway through. Failures after admission need their own handling, including idempotency where appropriate.

What a good no is made of

  1. Early and cheap. Run the admission check as early as your framework allows, ideally before expensive body parsing, database work or downstream calls. The refusal should be the fastest thing your service does.
  2. The right status code. 429 Too Many Requests means this caller has sent too many requests in a given time. 503 Service Unavailable means the server can't handle the request right now, for example because it is overloaded. The client's next move is different in each case, so don't mix them up.
  3. A Retry-After that means something. RFC 9110 allows either a number of seconds or an HTTP date. It is a hint, not a promise, and it is optional. Base it on a real estimate of when you can accept requests again. If you can't make a useful estimate, leave it out instead of inventing one.
  4. A body a program can read. RFC 9457 defines "problem details": a small JSON object with optional members such as type, title, status and detail, served as application/problem+json. A client can branch on type instead of grepping a message.
  5. A promise about side effects. If the admission check runs before your work function, you can say so in your docs: a refusal from this layer means the work function never ran. That makes retries much simpler. Be precise about it, though. Authentication, logging or other middleware may already have run, and a gateway or load balancer in front of you can return its own 503 for reasons you don't control. Write down which refusals carry the promise.

Request flow: the client's request reaches an admission check. If accepted, the work function runs and returns 200. If rejected, the work function never runs and the server returns 503 with Retry-After.

Here is the server side, using only the standard library. work is an async function that does the real job:

import json
from collections import Counter

MAX_IN_FLIGHT = 8
in_flight = 0
refusals = Counter()


def refuse(status, reason, retry_after_seconds=None):
    refusals[reason] += 1
    body = {
        "type": "https://example.com/problems/at-capacity",  # use a URI you control
        "title": "Temporarily at capacity",
        "status": status,
        "detail": "Refused at the admission check, before the work function was called.",
    }
    headers = {"Content-Type": "application/problem+json"}
    if retry_after_seconds is not None:
        if type(retry_after_seconds) is not int or retry_after_seconds < 0:
            raise ValueError("retry_after_seconds must be a non-negative integer")
        headers["Retry-After"] = str(retry_after_seconds)  # a hint, not a promise
    return status, headers, json.dumps(body)


async def handle(request, work):
    global in_flight
    if in_flight >= MAX_IN_FLIGHT:
        # first thing handle() does: the work function hasn't been called
        return refuse(503, "server_busy", 2)
    in_flight += 1  # nothing awaits between the check and this line
    try:
        return 200, {}, await work(request)
    finally:
        in_flight -= 1
Enter fullscreen mode Exit fullscreen mode

This is written for a single asyncio event loop, and the limit applies per process. The check and the increment can't be interleaved there, because nothing awaits between them. If you serve requests from several threads, or want one limit across several processes or machines, you need a different limiter. Treat the code as a teaching sketch, not a finished admission controller.

The 2 is a placeholder. Use a real estimate for your service, or pass nothing to leave the header out.

Taking a no well

A good customer takes a no well, too. That means reading the hint properly, waiting a little longer each time, adding some randomness so a crowd doesn't come back at the same second, and stopping eventually.

Retry-After comes in two forms, whole seconds or an HTTP date, so a client has to handle both:

import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime


def retry_after_seconds(value, now=None):
    if value is None:
        return None
    value = value.strip()
    if value.isascii() and value.isdigit():
        return float(value)
    try:
        when = parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    now = now or datetime.now(timezone.utc)
    return max(0.0, (when - now).total_seconds())


def polite_retry(send, safe_to_repeat, max_tries=4, max_total_wait=30.0):
    if max_tries < 1:
        raise ValueError("max_tries must be at least 1")
    if max_total_wait < 0:
        raise ValueError("max_total_wait must be non-negative")
    deadline = time.monotonic() + max_total_wait
    delay = 0.5
    for attempt in range(1, max_tries + 1):
        status, headers, body = send()
        if status not in (429, 503) or not safe_to_repeat:
            return status, headers, body
        if attempt == max_tries:
            return status, headers, body  # hand the no back; don't swallow it
        hinted = retry_after_seconds(headers.get("Retry-After")) or 0.0
        wait = max(hinted, delay)
        wait += random.uniform(0, wait / 2)  # jitter
        if not wait <= deadline - time.monotonic():
            return status, headers, body  # out of budget: hand the no back
        time.sleep(wait)
        delay *= 2
Enter fullscreen mode Exit fullscreen mode

This is a synchronous client, so it uses time.sleep; async code should use asyncio.sleep. It also assumes send() returns headers in a case-insensitive mapping, as requests and httpx do.

max_total_wait is a budget for the whole retry loop, and the time send() itself takes counts against it. If the next wait, or a Retry-After longer than what is left, would go past the budget, the client hands the no back instead of sleeping. The budget can't interrupt a send() that is already blocked, so give send() its own timeout.

safe_to_repeat is doing real work here. Reads, idempotent writes and calls carrying an idempotency key that the server actually enforces can be repeated. Ordering a coffee twice is not a retry. It's a bug with a receipt.

Count your nos

Every refusal should be counted, by reason. If refusals are handled quickly, their latency can stay low even as demand rises. The refusal count can be the graph that moves first when demand passes your limit. Keep watching latency for the requests you do accept, too, since a slow downstream can still stretch them. A no you don't count is a no you find out about from your customers.

It works on people, too

Everything above applies to the humans in your team. The Slow No is the request that sits in your inbox for three weeks. The Silent No is the unanswered message. The Vague No is "let's circle back." The Lying No is "sure!" followed by nothing. The Too-Late No arrives after the other person has built their plan on your yes.

A good no to a colleague has the same parts: early, quick, specific about what you're doing instead, honest about when they can ask again, and kind.

def can_you_just(ask):
    if ask["sounds_small"] and ask["touches_billing"]:
        # Not valid HTTP. Perfectly valid sprint planning.
        return 503, {"Retry-After": "next sprint"}
    return 200, {}
Enter fullscreen mode Exit fullscreen mode

A yes you can't deliver is just a slow no.

What's the best no you've ever received, from a system or from a person?

Top comments (17)

Collapse
 
xulingfeng profile image
xulingfeng The Third Cup •

Hey Shubhra! Look who's taking the seventh seat at The Third Cup! 🎉

Welcome aboard, my friend! I read your article, and now I'm wondering if I should start turning people away when they ask for free refills. Just kidding!😆

Make yourself at home. Your coffee is waiting. ☕The café is getting busier, and I couldn't be happier!

Collapse
 
shubhradev profile image
Shubhra Pokhariya The Third Cup •

Thank you so much for the warm welcome! I’ll try not to put the free-refill policy under too much pressure. 😄 Happy to have a seat at The Third Cup, and looking forward to the conversations and stories ahead. ☕

Collapse
 
xulingfeng profile image
xulingfeng The Third Cup •

Haha, don't worry! The seventh seat comes with unlimited refills. That's one café rule I'm never changing. 😂☕

Looking forward to your stories, Shubhra!

Thread Thread
 
shubhradev profile image
Shubhra Pokhariya The Third Cup •

Now that's a café rule I can happily get behind! 😄 Looking forward to sharing more stories here. ☕

Thread Thread
 
xulingfeng profile image
xulingfeng The Third Cup •

Then it's settled! 😂 Just bring the stories, and I'll take care of the coffee. Looking forward to many more cups and conversations! 🍻

Collapse
 
star123 profile image
Sᴛᴀʀ⭐ The Third Cup •

I really liked this post. Thank you! 😊

Collapse
 
shubhradev profile image
Shubhra Pokhariya The Third Cup •

Aww, thank you so much, Star! So happy you enjoyed it. Keep shining bright! ⭐😊

Collapse
 
leob profile image
leob The Third Cup •

Great write-up, and I love the cafe/bar metaphor! (or is it an analogy? well that's the same, probably)

P.S. interesting that there are even RFC's which standardize some of this stuff, e.g. RFC 9457 with its application/problem+json document definition! :-)

Collapse
 
shubhradev profile image
Shubhra Pokhariya The Third Cup •

Thank you so much, leob! 😄 Let's call it an analogy and let the grammar police enjoy their coffee in peace. RFC 9457 is basically the café's little "sorry, we're full" card, in a form even a client library can read. Even a rejection deserves good paperwork! ☕

Collapse
 
leob profile image
leob The Third Cup •

Thanks! I was surprised (in a good way) that even these kind of things are getting some "standards love" in the form of an official RFC ! :-)

Thread Thread
 
shubhradev profile image
Shubhra Pokhariya The Third Cup •

Same here, leob! 😄 Turns out even saying no deserves a standards committee! Glad our little café is keeping up with the RFCs. Always good to have you around ☕

Collapse
 
dafili profile image
Renhua Wei •

The right status codeisn't decided in your handler if nginx ownslimit_req: it answers 503 unless someone setlimit_req_status 429;, so a throttled caller is told "server can't handle it" and the dashboard pages on an outage that is really back-pressure.nginx -T | grep -n limit_req_status` prints nothing on a default config.

Collapse
 
shubhradev profile image
Shubhra Pokhariya The Third Cup •

Thanks for pointing that out, Renhua! The café's bouncer apparently has a habit of putting up the wrong sign 😄 When NGINX handles limit_req, it returns 503 by default. Setting limit_req_status 429; makes sure the sign tells customers what's actually happening. And your nginx -T | grep -n limit_req_status check is a handy way to catch it before the dashboard pages someone for a café that's merely full ☕

Collapse
 
hemapriya_kanagala profile image
Hemapriya Kanagala The Third Cup • • Edited

I loved the café examples, di 😀 And that last line, "A yes you can't deliver is just a slow no". So true!

Collapse
 
shubhradev profile image
Shubhra Pokhariya The Third Cup •

Aww, thank you, Hema! ❤️ Glad the café examples landed. That line deserves a little sign above the café door! Though I think a few sprint boards could use one too 😂

Collapse
 
technogamerz profile image
𝐓𝐡𝐞 𝐋𝐚𝐳𝐲 𝐆𝐢𝐫𝐥 The Third Cup •

Awesome Article!! :D

Collapse
 
shubhradev profile image
Shubhra Pokhariya The Third Cup •

Thank you, Divya! 😄 So glad you stopped by our little café. Hope you didn't get stuck in the slow queue ☕❤️