Library / Books
Building Secure and Reliable Systems
Designing, implementing and operating systems that are both secure and reliable.
By Google engineers · O'Reilly / Google · Added 2026-10-12
All content belongs to Google engineers / O'Reilly / Google. We only link to it and give credit. Report a problem
Learn this book
About 37 min left. Your work is saved as you go.
Why read this book now
O'Reilly / Google publishes this book. Choose a chapter that matches what you are studying now, rather than starting at page one.
Ideas you will meet
- Resilience
- Timeouts, retries, circuit breakers, bulkheads and load shedding.
- Web Security
- OWASP risks, XSS, CSRF, CORS and secure design.
What we already know about this
Our own lessons on these ideas. Read them here before you start, so it makes sense.
Advanced Distributed Systems · 13 minResilience: timeouts, retries, bulkheads, backpressure and circuit breakersHow to stop one slow or failing dependency from taking everything down: the patterns, how they fit together and where each one goes wrong.Read here
The core problem
In a system of many services, slowness is more dangerous than failure. A dependency that fails fast is easy to handle. One that responds in 30 seconds makes callers hold threads, connections and memory until they too stop responding: a cascading failure. Resilience patterns limit how far a problem can spread.
The toolbox
100%Figure SDA-ADS-06-1 · Resilience layers around a call · © forcsguy.com
Timeouts
Every network call needs a timeout, including connect, read and overall. Pick from measured latency (for example slightly above the 99th percentile), not a guess, and make the caller's budget smaller than its own caller's so work is abandoned in an orderly way. Propagate deadlines across calls.
Retries
Retry only transient failures and only idempotent operations (or use idempotency keys). Use exponential backoff with jitter (random spread) so clients do not retry in lockstep, cap the attempts, and apply a retry budget (for example no more than 10 percent extra traffic). Retry at one layer, not at every layer, or attempts multiply.
Circuit breaker
A breaker watches failures or slow calls. Closed: normal. After too many failures it opens: calls fail immediately (or use the fallback) so the dependency can recover and callers stop wasting resources. After a cool-down it goes half-open: a few trial calls decide whether to close again.
100%Figure SDA-ADS-06-2 · Circuit breaker states · © forcsguy.com
Bulkheads
Partition resources so one dependency cannot consume them all: separate thread pools or connection pools per dependency, separate queues per tenant or per priority, or separate instances for critical paths. A slow recommendation service then cannot starve checkout.
Backpressure and load shedding
If producers outpace consumers, work piles up. Without limits the buffer grows until memory is exhausted or latency becomes huge. Options:
- Bounded queues that reject or block when full.
- Signalling upstream to slow down (credit-based flow in streaming systems, TCP windows, reactive streams).
- Load shedding: deliberately drop low-priority work early (return 429 or 503 quickly) to protect the rest.
- Rate limiting at the edge (see the rate-limiter lesson).
Failing fast and visibly under overload is better than accepting everything and failing slowly.
Fallbacks and graceful degradation
Return something useful when a dependency fails: cached data, a default, a simpler algorithm, or hide a non-essential section. Decide which features are essential before an incident, and test the degraded mode.
How they interact
- A timeout is the minimum; without it nothing else works.
- Retries inside a breaker inside a bulkhead is the usual nesting.
- Everything needs metrics: breaker state, rejected calls, queue depth, timeout counts. Alert on them.
- Test it: inject latency and failures (chaos experiments) to confirm the patterns work before production does it for you.
Common mistakes
Retries with no backoff; timeouts longer than the caller's; unbounded queues; a shared thread pool for everything; breakers that never close; fallbacks that call the same failing service; and testing only the happy path.
Real-world reading
Related reading
- Timeouts, retries, and backoff with jitterAmazon Builders' Library · Amazon Web ServicesBlogs
- Using load shedding to avoid overloadAmazon Builders' Library · Amazon Web ServicesBlogs
- Circuit BreakerMartin FowlerBlogs
- Circuit Breaker patternMicrosoft · Microsoft AzureDocumentation
Show 6 moreShow fewer
- Google SRE Book: Addressing Cascading FailuresGoogle SRE team · GoogleBlogs
- Chaos Monkey (source)Netflix · GitHubGitHub
- Bulkheads: Partition and Tolerate Failure in One PartSkife engineers · SkifeCase Studies
- Protector: Circuit Breaker for Time Series Databases at TrivagoTrivago engineers · TrivagoCase Studies
- Autoscaling Jenkins at TrivagoTrivago engineers · TrivagoCase Studies
- Troubleshooting a Connection Timeout Issue with tcp_tw_recycle Enabled at eBayeBay engineers · eBayCase Studies
Networking and Web Security Deep Dive · 14 minWeb attacks: XSS, CSRF, injection, SSRF and clickjackingHow each major web attack works in plain terms and the few defences that stop most of them.Read here
Attacker mindset
Most web attacks share one cause: the application trusts input, or trusts the browser, more than it should. The fixes are few and repeatable. This lesson covers five of the most important attacks; the full checklist is in the OWASP lesson. (Authentication and sessions are in the passwords and securing-an-API lessons.)
1. Cross-site scripting (XSS)
What: attacker-controlled text is put into a page and the browser runs it as script. The script runs as your site, so it can read the page, act as the user and steal tokens.
Types: stored (saved in your database, such as a comment), reflected (echoed from a URL parameter), DOM-based (client-side code writes untrusted data into the page unsafely).
// vulnerable: untrusted text inserted as HTML el.innerHTML = comment.text; // <img src=x onerror=stealCookies()> runs! // safe: insert as text el.textContent = comment.text;Defences
- Escape output for its context (HTML, attribute, JavaScript, URL). Modern frameworks (React, Vue and others) escape by default; avoid raw-HTML escape hatches such as
dangerouslySetInnerHTMLorv-htmlwith untrusted data. - If you must allow rich text, sanitise with a well-maintained library and an allow-list.
- A Content Security Policy header limits where scripts can come from, reducing damage if something slips through.
- Mark session cookies HttpOnly so scripts cannot read them.
2. Cross-site request forgery (CSRF)
What: a malicious site makes the victim's browser send a request to your site, and the browser automatically attaches the victim's cookies. If the user is logged in, the action happens (change email, transfer money).
100%Figure SDA-NSD-03-1 · How CSRF works and how a token stops it · © forcsguy.com
Defences
- SameSite cookies (
LaxorStrict) stop browsers sending cookies on most cross-site requests; now the browser default for many cases but set it explicitly. - Anti-CSRF tokens: a random value tied to the session that must accompany state-changing requests.
- Never change state with
GET; check theOriginheader; require re-authentication for sensitive actions. - APIs that use an
Authorizationheader (not cookies) are not vulnerable in the same way, because the browser does not attach it automatically.
3. Injection (SQL, command, and others)
What: input is concatenated into an interpreter's command, so the input changes the command's meaning.
// vulnerable db.query(`SELECT * FROM users WHERE email = '${email}'`); // email = ' OR '1'='1 returns everyone // safe: a parameterised query keeps data and command separate db.query("SELECT * FROM users WHERE email = $1", [email]);Defences
- Parameterised queries / prepared statements for SQL; ORMs do this for normal calls (beware raw-SQL escape hatches).
- Avoid building shell commands from input; use library calls with argument arrays, not strings.
- Validate input against an allow-list of expected formats, and apply least privilege to database accounts (the web app should not be able to drop tables).
- The same pattern applies to NoSQL queries, LDAP, XML and template engines. Rule: never build code or queries by joining strings with untrusted data.
4. Server-side request forgery (SSRF)
What: the app fetches a URL supplied by the user (a preview, an image import, a webhook test). The attacker supplies an internal address; the server, which sits inside your network, fetches it and may return secrets, such as cloud instance credentials from the metadata endpoint, or probe internal services.
Defences
- Prefer an allow-list of destinations; if not possible, block private, loopback and link-local ranges after resolving the name, and re-check on every redirect (and beware of DNS tricks that change the answer between check and use).
- Allow only
httpandhttps; set short timeouts and size limits. - Run fetchers in an isolated network with no route to sensitive services; use cloud settings that require a session token for metadata access.
- Do not return the raw response to the user.
5. Clickjacking
What: your page is loaded in a hidden or disguised frame on an attacker's site, and the user is tricked into clicking buttons they cannot see (like "delete account").
Defences
- Send
Content-Security-Policy: frame-ancestors 'none'(or'self'), and the olderX-Frame-Options: DENY. - Require confirmation for sensitive actions.
One table to remember
Attack Root cause Main defence XSS Untrusted data becomes script in a page Output escaping, CSP, HttpOnly cookies CSRF Browser sends cookies on forged requests SameSite cookies, anti-CSRF tokens Injection Data joined into a command Parameterised queries, validation, least privilege SSRF Server fetches attacker-chosen URLs Allow-lists, block internal ranges, isolation Clickjacking Page framed by another site frame-ancestors / X-Frame-Options Habits
- Defence in depth: assume one layer will fail.
- Validate on the server always; client checks are only for user experience.
- Use framework defaults and keep dependencies updated.
- Log and alert on suspicious input patterns and blocked requests.
- Test: automated scanners, code review checklists and, for important systems, independent penetration tests.
Real-world reading
Related reading
- MDN: Cross-Origin Resource Sharing (CORS)MDN contributors · MozillaDocumentation
- OWASP Cheat Sheet SeriesOWASP · OWASP FoundationDocumentation
- OWASP Top 10OWASP · OWASP FoundationDocumentation
- Introduction to JSON Web TokensAuth0 · jwt.ioDocumentation
Show 6 moreShow fewer
- High Performance Browser NetworkingIlya Grigorik · O'ReillyBooks
- RFC 9114: HTTP/3IETFDocumentation
- Building Secure and Reliable SystemsGoogle engineers · O'Reilly / GoogleBooks
- RFC 6749: The OAuth 2.0 Authorization FrameworkIETFDocumentation
- Syscall Auditing at Scale at SlackScale at Slack engineers · Scale at SlackCase Studies
- MySQL High Availability at GitHubGitHub Engineering · GitHubCase Studies
- Escape output for its context (HTML, attribute, JavaScript, URL). Modern frameworks (React, Vue and others) escape by default; avoid raw-HTML escape hatches such as
Networking and Web Security Deep Dive · 13 minThe OWASP Top 10 and secure designA map of the most common web application risks, what each means in practice and a short review checklist you can apply to any design.Read here
What the Top 10 is
OWASP (the Open Worldwide Application Security Project) publishes an awareness list of the most critical web application risks, updated every few years from real data. Treat it as a checklist of categories to think about, not a complete standard. The names and order change between editions, so below the themes are described in stable terms with the current style of names in brackets.
The recurring risk categories
100%Figure SDA-NSD-05-1 · The risk categories as a review map · © forcsguy.com
Category In plain words Typical prevention Broken access control Users can act outside their permissions (view others' data, call admin features) Check authorisation on the server for every request and object; deny by default; test with two users Cryptographic failures Sensitive data exposed (no TLS, weak or home-made crypto, plaintext storage) TLS everywhere, strong standard algorithms, hash passwords with a slow salted hash, manage keys properly Injection Input interpreted as code or commands Parameterised queries, validation, least privilege (see the attacks lesson) Insecure design The design itself lacks controls Threat modelling, abuse cases, secure patterns, limits on resources Security misconfiguration Default passwords, open storage buckets, verbose errors, missing headers Hardened baselines, infrastructure as code, regular scans Vulnerable and outdated components Known flaws in libraries or platforms Inventory dependencies, update, use automated advisories Identification and authentication failures Weak passwords, no MFA, bad session handling MFA, rate limiting, safe recovery, strong session management Software and data integrity failures Untrusted updates, insecure CI/CD, unsafe deserialisation Signed artefacts, protected pipelines, verify dependencies Security logging and monitoring failures Attacks go unnoticed Log security events, alert, practise incident response Server-side request forgery The server fetches attacker-chosen URLs Allow-lists, block internal ranges, isolation Authentication, authorisation, encryption, hashing
- Authentication answers "who are you?"; authorisation answers "what may you do?". Do both on the server, every request.
- Encryption is reversible with a key (protect data in transit and at rest). Hashing is one-way (verify without storing the original): for passwords use a slow, salted algorithm such as Argon2, bcrypt or scrypt, never plain SHA of the password. A salt is a unique random value per password that defeats precomputed tables. (Details in the passwords lesson.)
- Never invent your own cryptography.
Secure design in practice
- Threat model early. Draw the data flows, list assets, ask "who might attack this and how?" (a simple method: for each component consider spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege).
- Least privilege everywhere: users, services, database accounts, cloud roles.
- Defence in depth: several independent controls.
- Secure defaults: deny first; features off until needed.
- Fail safe: on error, do not grant access; do not leak details.
- Minimise data: do not collect or keep what you do not need.
- Automate: dependency scanning, static analysis, secret scanning, container scanning in CI.
- Test: unit tests for authorisation rules, automated scans, periodic penetration tests.
- Prepare for incidents: logs, alerts, runbooks, key rotation, backups.
A short review checklist for any feature
- Who is allowed to do this, and where is that checked?
- What input comes from users, and how is it validated and encoded?
- What secrets and personal data are involved, and how are they protected and logged?
- What can an attacker abuse in volume (rate limits, size limits, cost)?
- What third-party code or services does it add, and are they maintained?
- How would we notice if it were abused?
Where this fits
Security is a property of the whole system: network edge (previous lessons), application code (attacks lesson), identity (SSO and passwords lessons), data (encryption) and operations (monitoring and incident response). Make it a routine part of design reviews, not a final gate.
Real-world reading
Related reading
- OWASP Cheat Sheet SeriesOWASP · OWASP FoundationDocumentation
- AWS Security BlogAmazon Web Services engineers · Amazon Web ServicesBlogs
- Google Security BlogGoogle engineers · GoogleBlogs
- OWASP Top 10OWASP · OWASP FoundationDocumentation
Show 6 moreShow fewer
- Building Secure and Reliable SystemsGoogle engineers · O'Reilly / GoogleBooks
- Athenz: Fine-Grained, Role-Based Access Control at YahooYahoo engineers · YahooCase Studies
- Scalable IAM Architecture to Secure Access to 100 AWS Accounts at SegmentSegment engineers · SegmentCase Studies
- Security Development Lifecycle at SlackSlack engineers · SlackCase Studies
- Centralized Application Logging at eBayeBay engineers · eBayCase Studies
- Enterprise Key Management at SlackSlack engineers · SlackCase Studies
Go deeper on this
A path through videos, articles, other case studies and code on the same ideas as Building Secure and Reliable Systems.
Warm upGet the vocabulary first.
Books · Free from the author
Security Engineering
How to build systems that stay secure when things go wrong: threat models, protocols, access control and failures. The author publishes the book free online.
University of CambridgeAdvanced
Documentation
RFC 6749: The OAuth 2.0 Authorization Framework
The standard defining OAuth 2.0 roles and flows.
IETFAdvanced
WatchHow others solve the same problem, on video.
Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)
ReadEngineers explain it in their own words.
Blogs
Google SRE Book: Handling Overload
Client-side throttling, per-client quotas and criticality levels for staying up when demand exceeds capacity.
GoogleAdvanced
Blogs
Avoiding fallback in distributed systems
Why rarely used fallback paths often fail when needed, and what Amazon does instead.
Amazon Web ServicesAdvanced
See it in another companyThe same ideas, a different system.
Case Studies · Read here
10 Tips for Building Resilient Payment Systems
Practical rules from Shopify's payments team: idempotency, retries, reconciliation and more.
ShopifyIntermediate
Case Studies · Read here
Clock Skew when Syncing Password Payloads at Drobbox
How Dropbox Passwords fixed sync errors from clock skew by replacing a two-way timestamp merge with a three-way merge against a base payload.
DrobboxIntermediate
Read the codeSee how it looks when it is real.
GitHub
Chaos Monkey (source)
The source of Netflix's tool for randomly terminating instances to test resilience.
GitHubIntermediate
Keep learning
Loading community…