What goes into a legible REST 4xx response?

Knowing that a route returned a 4xx status code doesn’t tell you why that 4xx happened. Perhaps that 4xx was a good result. Imagine a route that checks to see whether a username is available: A 404 NotFound is what we want to happen!

This makes it complicated when we set up alerts on our backend. We don’t want to trigger an alert about high 404s because our signup flow’s username check is working well. And we don’t want to trigger an alert on high 410 Gones because a user is repeatedly trying to use an expired password link.

Solid frontend error instrumentation goes a long way here. The frontend is a natural spot for logic about whether any given status code is expected or a disaster. At smaller scales, relying primarily on frontend instrumentation to detect problems can work well! But that approach can break down as the team and scale grows: you end up with more routes, more people, and more clients hitting a backend, and some of these clients won’t necessarily be under your control.

This means 4xx responses need to be legible. The shape of the response should make it easy to tell whether something is broken and which team should handle any fixes.

A status code isn’t enough. We need a reason

We started with the idea that a 404 on one route might be expected, and a 404 on another route could be a major problem. Many routes have multiple reasons that they return the same status code. Picture a route where a user signs up for text message updates. A 400 might mean:

In our observability layer, if we only store that this POST returned a 400, we won’t have a way to easily investigate a spike in 400s.

The client will need to update the UI differently depending on which type of 400 it received. We can do that in an ad-hoc way – maybe checking for a string on an error message in the body – but it’s much nicer to have a standardized reason field baked into the type system that client code can use when deciding how to handle the error.

// on the backend
throw Response.BadRequest({
    expected: true,
    reason: "err_landline",
});

// on the client
try {
    await makeRequest("POST", "/register-phone-number", { number })
} catch (err) {
    if (err.body.reason === "err_landline") {
        return handleLandlineError({ number, err });
    }

    return handleUnhandledError(err);
}

Coupled with the idea that some reasons are expected, we now have a useful definition for our clients about which 4xx response reasons it needs to handle. Any route might return response codes like a 401 (if a user’s session expired) or a 403 (if permissions changed), but those can be left to whatever default error-handling we have in place. If we use something like the OpenAPI Specification (née Swagger) to generate a type definition of our backend that includes reason and expected, we can use types or a custom lint rule to enforce that every expected 4xx response is well-handled across every client.

💬

There’s a reason that some companies return 200s for everything and distinguish the case in the response body. Response status codes aren’t enough by themselves, but I still like them as a categorization scheme. When I see a common status code like 400, 403, or a 504, I immediately know the problem category and possible debugging steps.

Fallback error messages for breaking changes

It’s a bummer when you need to make breaking changes to a route, but it happens. Say you start requiring a second factor of authentication for users logging in from surprising locations – older clients won’t have the code in place to handle that 401 reason and will fall back to a generic "something went wrong" error message. This isn’t a good experience for your users.

A pattern I like is allowing the backend to supply a custom error message that the clients will use rather than its generic error message:

throw Response.Unauthorized({
    expected: true,
    reason: "err_2fa_required_new_location",
    fallbackErrorMessage: `<b>Please check your email for a 2FA login link.</b> It looks like you're logging in from somewhere new, and we want to keep your account secure.

If you upgrade your app version, you'll be able to configure your 2FA settings and enjoy an easier login experience.`
})

If the client can handle err_2fa_required_new_location without using that fallback error message, all the better! It takes a long time for users to upgrade their app versions, and breaking changes with generic error messages can be one of the most frustrating experiences for a user.2

Some fallback error messages might be a good-enough experience for some use-cases. When the client exhaustively goes through all of the possible expected reasons for a 4xx response, it may be reasonable for some cases to simply use that fallback error message directly, although it’s still nice to do so explicitly so we can enforce that we’ve put thought into how every 4xx response reason is handled by the client.

try {
    await makeRequest("POST", "/session", { login, password })
} catch (err) {
    if (err.body.reason === "err_2fa_required_new_location") {
        return showErrorScreen(err.body.fallbackErrorMessage);
    }

    // if we're enforcing exhaustive client expected error handling at the type level
    assertUnreachableClientError(err);

    // even though `handleUnhandledError` will use the `fallbackErrorMessage`,
    // it will also track this problem as an error!
    // and we want to have a type or lint rule that enforces that we exhaustively handle any expected error messages
    return handleUnhandledError(err);
}

function assertUnreachableClientError (err: never) {}
💡

These messages can even be translated! A system I’m proud of from ClassDojo parsed the TypeScript AST to pull out the fallbackErrorMessage strings, used those to construct a JSON file keyed by the hashed versions of the strings, uploaded that file for translation, and then had a middleware replace the error message with its translated version.

Some companies handle this case with a 426 Upgrade Required response. Technically, 426 is a response code about the protocol, but it’s still a common way of informing clients that something won’t work until they upgrade. I like the flexibility of the backend being able to supply error messages, but a system that just handles 426s or any other standardized response with a "Please upgrade" message is simple to implement.

What other tags do we want?

At this point, our 4xx responses are tagged with whether they’re expected, are broken down by reason, and have fallback error messages for older clients. They’ll be reasonably easy to build alerts and dashboards for, but there are five more fields (beyond common ones like platform, app version, or browser) that can simplify observability and setting up alerts:

  1. request_uuid: Every request should have a distinct identifier that makes it easy to match up logs across the frontend and backend.
  2. cardinalityId: A single user causing 10,000s of errors is a problem, but we should handle that case differently than 10,000s of users hitting a single error. Using userId to manage cardinality can help, but it’s ergonomic to have a single field that spans logged in and logged out users. For logged-out users this can be a browser fingerprint, a cookie, a deviceId, a (hashed) IP address, or anything else that gives a unique-ish identifier to a single client.3
  3. flow/product_area: When we set up dashboards or alerts, we’ll often want to focus in on a particular set of routes. This can sometimes be handled by route prefixes, but it’s ergonomic to have it as its own field for metrics and logs.
  4. team: When something goes wrong, we want to make it easy to send alerts and logs to the right people. (Teams change over time, so we don’t necessarily want to tag the route itself with the team – that ownership might change. Having a mapping layer from flow/product_area to team can make ownership changes slightly simpler)
  5. user_experiments: A new experiment can be a common source of unexpected client errors, and it’s useful to be able to easily slice and dice performance by experiment variant. This is more complicated to set up, but it’s broadly useful across logs and traces.
💡

As the number of teams and flows grows, it can be helpful to manage alerts based on these fields through Infra as Code. When alerting on unexpected 4xx responses, each team will have its own alert destinations, and teams may have different acceptable levels of errors that they’ll want to ratchet and manage on their own. A team working on a greenfield project may want to alert on any unexpected error, while a team maintaining a larger set of legacy routes might need a higher level while the team burns those alerts down. It’s useful to have one IaC definition of the alert with per-flow or per-team configuration.

I’ve enjoyed using Pulumi for this in the past. One idea I’d like to explore more in the future is setting up the alerting configuration for routes on the route itself and making alert definitions an intrinsic part of the codebase. E.g., when we have any logger.warn call, should we also always configure the level of warnings at which we want to be alerted for that warning?

Knowing when things are broken is what matters

Depending on your current scale, some of this could be excessive! Having instrumentation isn’t an end goal by itself – knowing when something is broken and who should fix it is.

There’s more than one way to achieve that goal. You don’t need to build this from scratch. A tool like Sentry could make it relatively straightforward to set up a system that meets these needs, but even with that sort of tool, you need a clear idea of how you want it to work.

Detecting when clients are using a route incorrectly makes it easier to fix that problem. Legible 4xx responses help make that happen.

Field Description
expected Is this a bug on the client? Or is the route doing what it’s supposed to?
reason What’s the precise cause of this 4xx?
fallbackErrorMessage If a client doesn’t know how to handle a particular reason, what message should it show?
request_uuid Distinct identifier across frontend and backend.
cardinalityId Identifier for logged out users / userId that allows alerting on the cardinality rather than volume of errors.
flow/product_area What product area does this route belong to?
team Who should fix it when it’s broken?
user_experiments Which experiments is the user in?

  1. Be wary of SMS Pumping Fraud! You can rack up gigantic bills very quickly if a fraudster abuses an insufficiently secured route. ↩︎

  2. I’m surprised at how bad many applications' generic error messages are. They generally don’t tell users the "standard" debugging steps of upgrading the app or trying a different browser and/or incognito window. An error message like "Uh-oh, something went wrong." is infuriating because it doesn’t give users the tools to solve their own problem or give them any confidence that someone will actually be digging into the issue. ↩︎

  3. For IP address, be aware of legal requirements if you’re operating in the EU, UK, or Canada (or any other country that has similar regulations). By itself, an IP can be considered PII in those jurisdictions, so you’ll need things like a clear usage policy, retention limits, and access rules. IP addresses are often helpful, but it’s a field that you need to be thoughtful about. ↩︎