Error handling and defensive design
Sort errors into the ones you expect and the bugs, handle each kind on purpose, and never hide one.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 12 June 2025, many Google Cloud APIs started to return errors around the world. The cause was one part of Service Control, the system that checks quota and policy for incoming API requests. 1
On 29 May, Google had added a new quota check to Service Control. It rolled out region by region, but the code path that failed never ran. It needed a certain policy change to trigger it. 1
The report says this change had no proper error handling, and it was not protected by a feature flag. 1
On 12 June, a policy change was copied to every region within seconds. The policy data had blank fields that nobody intended. The new code read a blank field and hit a null pointer. The report says that "without the appropriate error handling, the null pointer caused the binary to crash." 1
The binaries restarted, read the same data and crashed again: a crash loop. In big regions, the restarting tasks all hit the database table they depend on at once. Service Control did not have randomized exponential backoff to prevent this. Full recovery in us-central1 took up to about 2 hours 40 minutes. 1
Google's fixes include better error handling and testing for invalid data. They also say parts of Service Control should "fail open" when they break. 1
It happens for real
Google Cloud · 12 Jun 2025Google Cloud outage: blank policy fields crashed API checksFor hours, many Google Cloud and Workspace APIs returned 503 errors across the world, touching 76 Cloud products. CrowdStrike · 19 Jul 2024CrowdStrike outage: a content update crashed Windows hostsWindows machines running the Falcon sensor crashed to a blue screen, and many needed manual fixes to start again. All incidents tagged “config”The idea in simple words
Errors come in two kinds, and you should handle them differently.
- Expected errors happen in normal life. A user types a wrong date. A file is missing. Another service is busy for a moment. Your code should plan for these and handle them.
- Bugs are broken assumptions. A value that "can never be empty" is empty. An index is past the end of a list. Retrying will not fix a bug. A person has to fix the code.
Rust's official book uses the same split. It calls them recoverable and unrecoverable errors. It says unrecoverable errors "are always symptoms of bugs." 2
The key idea. Decide on purpose what happens for every error. Handle the expected ones close to where you can do something useful. Make bugs loud, so a person sees them and fixes them. Never hide either kind.
Never swallow errors. An empty catch block, or a "log and return null" with no plan, hides the problem. The program carries on in a bad state, and the real failure shows up later, far away, where it is much harder to debug.
How it works
Step through a request where one downstream call fails. Watch how each layer decides what to do. Use Next and Back, or the ← and → keys.
- The phone app asks for product 42. The Product API needs a delivery date, so it calls the Delivery service with a timeout of 300 ms.
- The Delivery service answers 503: busy. The API classifies the error. A 503 on a read is transient and safe to retry. A 400 would be a different story: the request is wrong, so a retry cannot help.
- The API retries once, after a short backoff with jitter. It retries in this layer only. The second call times out.
- The retry limit is reached, and the user is waiting. The delivery date is optional on this page, so the API degrades: it builds the page without a date, instead of failing the whole page.
- The user gets the product page with a short, calm message. Engineers get a log line with the error, the number of tries and the request ID. No stack trace or secret goes to the user.
Validate input at the boundary
Check data where it enters your system, before any business logic uses it. Check the shape (type and format) and the meaning, for example "the end date is after the start date". Define what you accept and reject everything else. 8
Do this on the server, even if the browser already checks the same field. OWASP also says to validate data from internal APIs, partner feeds, queues and stored records when it crosses a trust boundary. 8 The Google Cloud policy data came from inside Google, and it still had blank fields. 1
Errors are part of your API
Give each error a type or code that tells the caller what it can do next. Three questions cover most cases:
- Can I retry? For example, "service busy" or a timeout.
- Must I change the request? For example, "invalid email" or "amount too large".
- Is this a bug on your side? Then the caller can only report it.
For HTTP APIs, RFC 9457 gives a standard JSON shape for this, called problem details. It has fields such as type, title, status and detail. 9 The REST API lesson covers status codes.
Exceptions or result values
Some languages throw exceptions. Others, like Rust and Go, return an error as a normal value. Rust's book gives a simple rule that works in any language. When failure is expected, return an error value, so the caller must decide what to do. Its examples are a parser given bad data and an HTTP call that hits a rate limit. When a contract is broken, stopping is reasonable, because it shows a bug in the caller. 3
The style matters less than one habit: every error must be visible in the code that calls the function.
Fail fast or degrade gracefully
Fail fast means you stop at the first sign of trouble with a clear error. Do this for bugs, bad config at startup, and requests that are too large. Google's SRE book advises that under overload you should "fail early and cheaply." 4
Graceful degradation means you still serve the user, with less. A product page can show without recommendations. The SRE book says degraded mode "shouldn't trigger very often", and that you should test it. 4
The choice depends on the feature. A missing recommendation is fine. A missing fraud check on a payment is not.
Retries, timeouts, circuit breakers and fallbacks
Retries. Retry only transient errors, the ones that may pass in a moment. Do not retry client errors or malformed requests, because the same request will fail again. 4 5 Calls that change data need idempotency first. The idempotency and retries lesson covers keys, backoff and retry limits.
Timeouts. Put a timeout on every remote call. Amazon's advice is to set a timeout on any remote call, and in general on calls between processes on the same machine too. 5 Better still, pass a deadline down the call chain, so lower services stop work the user has already given up on. 4
Circuit breakers. A circuit breaker stops calls to a service that keeps failing, for a short time. This protects the failing service and saves your threads. Amazon notes a cost: breakers add modal behavior that is hard to test, and they can slow recovery. 5
Fallbacks. A fallback is a second way to get the answer, used only when the first way fails. Amazon usually avoids them. Fallback code is hard to test and may rarely run in production, so it can hide bugs. In an Amazon outage around 2001, web servers fell back to a database when their caches failed. They all hit the database at once, and the whole website went down. 6
Amazon prefers to make the main path more reliable, or to run both paths all the time, which turns the fallback into failover. If a fallback is essential, Amazon exercises it as often as possible in production. 6
Messages for users, logs for engineers
Users and engineers need different things. The user needs a short, calm message and a next step: "We could not load delivery dates. Please try again." Engineers need the details: error type, which call failed, how many attempts, and a request ID.
Never send stack traces, SQL errors or server versions to users. They help attackers learn your system. Return a generic response and log the details on the server. 7 Also keep secrets, tokens and personal data out of error messages and logs. The observability lesson covers what to log.
Trade-offs
| Approach | Good for the user? | Risk | Use it when |
|---|---|---|---|
| Fail fast | No They see an error now. | Low. The problem is clear and close to its cause. | Bugs, bad config at startup, invalid input. |
| Retry | Yes , if the error was brief. | Retries add load to a struggling service. | Transient errors on idempotent calls, with a limit. |
| Degrade gracefully | Yes They get most of the page. | The degraded path may be untested. | Optional parts, like recommendations or reviews. |
| Fallback to another source | Yes , if the fallback works. | Rarely run code can fail or overload a shared system. | Only when you run and test it often. |
| Swallow the error | No Wrong results later. | High. Nobody knows something broke. | Never. |
Simple rule: for each call that can fail, write down which errors are expected and what happens for each. Everything else is a bug, and a bug should fail loudly.
At work: how a senior uses this
- In code review, ask about every
catch: "What does the caller see, and what do we log?" An emptycatchis a finding. - Ask "What happens if this field is empty?" for data from files, configs and other teams, not only from users.
- Check that every remote call has a timeout, and that retries happen in one layer only.
- Mark each dependency as critical or optional. Optional ones get a degraded mode. Critical ones fail with a clear error.
- Make sure a degraded mode shows up on a dashboard, so it does not stay on for weeks unseen.
- Keep one error format across all your APIs, with a code and a request ID in every response.
With AI
What to ask the agent
"List every place in this module where an error is caught and ignored, logged without being returned, or turned into null. For each one, say what the caller will see."
"For each remote call in this service, list the timeout, the retry policy and what happens on failure. Mark calls with no timeout."
"Write tests that send empty, missing and oversized fields to this parser. Each test must expect a clear validation error, not a crash."
What to check yourself
- The agent did not add broad
catchblocks that hide errors to make tests pass. - Retries are only on transient errors and only on idempotent calls.
- Error responses do not contain stack traces, SQL, tokens or personal data.
- New fallback code has a test that makes the main path fail.
- Validation is on the server, at the boundary, not only in the client.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 9 sources and related lessons
- Google Cloud, Service Health incident report for 12 June 2025 (official) (opens in a new tab)
How blank fields in policy data hit a null pointer with no error handling and crashed API checks around the world. - The Rust Programming Language (official book), chapter 9 “Error Handling” (opens in a new tab)
Recoverable and unrecoverable errors, and why bugs should stop the program. - The Rust Programming Language (official book), section 9.3 “To panic! or Not to panic!” (opens in a new tab)
When to return an error value and when to stop, with examples from parsers and rate limits. - Mike Ulrich, “Addressing Cascading Failures”, Site Reliability Engineering (O'Reilly), chapter 22 (opens in a new tab)
Which errors to retry, deadlines, failing fast and graceful degradation under overload. - Marc Brooker, “Timeouts, retries and backoff with jitter”, Amazon Builders' Library (opens in a new tab)
Transient errors, why client errors are not worth a retry, how to pick a timeout, and the cost of circuit breakers. - Jacob Gabrielson, “Avoiding fallback in distributed systems”, Amazon Builders' Library (opens in a new tab)
Why rarely used fallback code is risky, and what Amazon does instead. - OWASP Cheat Sheet Series, “Error Handling Cheat Sheet” (opens in a new tab)
Why detailed errors help attackers, and the generic-response-plus-server-log pattern. - OWASP Cheat Sheet Series, “Input Validation Cheat Sheet” (opens in a new tab)
Syntax and meaning checks, allowlists, and validating data from internal systems too. - IETF RFC 9457, “Problem Details for HTTP APIs” (July 2023) (opens in a new tab)
A standard, machine-readable shape for error responses in HTTP APIs.
Real incident: Google Cloud, 12 Jun 2025: Google Cloud outage: blank policy fields crashed API checks
Real incident: CrowdStrike, 19 Jul 2024: CrowdStrike outage: a content update crashed Windows hosts
Related: Idempotency, retries and timeouts · Safe deploys and config changes · Observability, SLOs and error budgets · OWASP Top 10 and secure coding · REST API design
Related lessons: Idempotency and retries, Safe deploys, Debugging production and Secure coding.