Lessons
1 · System Design Foundations
2 · APIs and Communication
3 · Capacity Estimation
4 · Core Building Blocks
5 · Databases
- 12Relational Databases and Data Modeling for System Design
- 13Database Indexes and Query Performance: How to Make Reads Fast
- 14Transactions, Isolation Levels and Concurrency Control: Preventing Race Conditions
- 15Database Replication: Primary-Replica, Read Replicas, Lag and Failover
- 16Database Sharding and Partitioning: How It Works and When You Need It
- 17SQL vs NoSQL: Data Models and How to Choose the Right Database
6 · Distributed Systems
- 18Why Distributed Systems Are Hard: Partial Failure, Timeouts and Clocks
- 19CAP Theorem and Consistency Models Explained Without the Myths
- 20Idempotency, Retries and Message Delivery Guarantees
- 21Distributed Transactions: Two-Phase Commit, the Outbox Pattern and Sagas
- 22Distributed Locks, Leases, Leader Election and Consensus
7 · Reliability and Operations
8 · Architecture and Security
9 · Interview Method and Foundation Case Studies
10 · Real-World Case Studies
- 33Design a Notification System: Email, SMS and Push at Scale
- 34Design a Chat System Like a Messaging App
- 35Design a News Feed: Fan-Out, Ranking and the Celebrity Problem
- 36Design Search Autocomplete (Typeahead)
- 37Design a Distributed Job Scheduler
- 38Design a Ticket Booking System Without Overselling
- 39Design a Payment System: Idempotency, Ledgers and Reconciliation
11 · Large-Scale Case Studies
- 40Design a Video Streaming Platform: Upload, Transcoding and Adaptive Streaming
- 41Design a Ride-Hailing System: Location, Matching and Real-Time Updates
- 42Design a Food Delivery Platform: Orders, Restaurants and Delivery Partners
- 43Design an E-Commerce System: Catalog, Cart, Checkout, Inventory and Flash Sales
- 44Design a Web Search Engine: Crawling, Inverted Indexes and Ranking
12 · Interview Readiness
Lesson 28 · Architecture and Security
Security in System Design: Authentication, Authorization, Encryption and Abuse Prevention
The security decisions that shape an architecture: trust boundaries and least privilege, authentication with passwords, MFA and identity providers, sessions versus tokens and JWTs, object-level authorisation, service-to-service identity, encryption in transit and at rest, secrets management, input validation and abuse prevention, SSRF, data privacy, audit logs and payment data.
For
SDE-2 candidates and backend developers who need to make and explain the security decisions in a design, without becoming security specialists.
Level
Before you start
Read API Design (article 04), Load Balancers (article 08) for TLS termination and statelessness, and Observability (article 25) for logging. Monolith vs Microservices (article 26) introduces the API gateway used here.
On this page
Key takeaways
- Authentication proves who a caller is; authorisation decides what they may do, and must be checked for every object, not just every endpoint.
- Server-side sessions are easy to revoke; self-contained tokens such as JWTs avoid a lookup per request but are hard to revoke, so keep them short-lived and validate them strictly.
- Encrypt everything in transit, encrypt sensitive data at rest with managed keys, and keep secrets out of code and images, with rotation.
- Defend against abuse with validation, size limits, rate limits and care whenever the server fetches a user-supplied URL.
- Collect less personal data, know where it lives, log security-relevant actions to protected audit logs, and keep card data out of your systems where possible.
A developer notices that the URL for their own order is /api/orders/1043. Out of curiosity they try /api/orders/1042, and see a stranger's name, address and purchases. The API checked that the caller was logged in. It never checked that order 1042 belonged to them. This flaw is so common that OWASP lists it first among API security risks.
Security in system design is not about memorising attacks. It is about a small set of architectural decisions (who can call what, how identity is proven and carried, where secrets live, what is encrypted, what is logged) made deliberately and checked at every boundary. This article covers those decisions at the depth an SDE-2 interview expects. It is not a penetration-testing course.
What you will learn
#- Security principles that shape architecture: trust boundaries, least privilege, defence in depth.
- Authentication: passwords, multi-factor authentication and identity providers.
- Sessions versus tokens, and how to use JWTs safely.
- Authorisation: roles, attributes and per-object checks, and the OWASP API Top 10.
- Service-to-service identity and zero trust.
- Encryption in transit and at rest, and secrets management.
- Input validation, abuse prevention and SSRF.
- Privacy, audit logs and payment data.
Principles that shape the architecture
#- Trust boundaries: draw where data crosses from less trusted to more trusted zones (internet to gateway, gateway to service, service to database, your system to a third party). Every boundary validates input and authenticates the caller.
- Least privilege: every user, service and credential gets only the permissions it needs. A thumbnail worker needs to read uploads and write thumbnails, not to delete accounts.
- Defence in depth: assume any one control can fail; layer them (edge filtering, authentication, per-object authorisation, encryption, monitoring).
- Secure defaults: private by default (buckets, APIs, new features), deny by default for authorisation.
- Minimise the attack surface: fewer exposed endpoints, ports, admin paths and stored secrets.
A simple threat-modelling habit in interviews: for each main flow, ask what an attacker would want (data, money, disruption), where they could enter, and what stops them.
Authentication: proving who the caller is
#Authentication (authn) establishes identity. Authorisation (authz) decides permissions. They are different questions, answered by different code, and confusing them causes the opening bug.
Passwords, if you must store them
#- Store only a slow, salted hash, never the password or a fast hash. OWASP's password-storage guidance recommends algorithms designed for this purpose, such as Argon2id, scrypt or bcrypt (and PBKDF2 where required), with appropriate work factors (Password Storage Cheat Sheet).
- Rate-limit login attempts per account and per source, and watch for credential stuffing (attackers trying leaked passwords from other sites).
- Offer multi-factor authentication (an authenticator app, a passkey or hardware key, or less preferably SMS) for anything valuable.
- For authenticator and assurance-level requirements, NIST's Special Publication 800-63B-4 (published in 2025) is the reference many organisations follow (NIST SP 800-63B-4).
Prefer an identity provider
#Building authentication well is hard. Many systems delegate it to an identity provider (a managed service, a company directory, or "sign in with" a large provider) using standard protocols:
- OAuth 2.0 is an authorisation framework that lets an application obtain limited access to a resource on a user's behalf, using access tokens (RFC 6749). Its current security best practice is RFC 9700 (OAuth 2.0 Security Best Current Practice).
- OpenID Connect adds an identity layer on top of OAuth 2.0, so the application learns who the user is through an ID token (How OpenID Connect works).
In a design, you can say: "users authenticate with our identity provider via OpenID Connect; the API gateway validates access tokens; services trust the gateway-validated identity and check authorisation themselves."
Sessions versus tokens
#After login, every request must carry proof of identity. Two families:
Server-side sessions
#The server creates a random session id, stores session data server-side (for example in Redis, so any stateless app server can read it, article 08), and sends the id in a cookie.
- Revocation is easy: delete the session; the user is logged out everywhere immediately.
- Every request needs a lookup in the session store.
- Cookies should be marked
Secure(HTTPS only),HttpOnly(not readable by page scripts) and given an appropriateSameSitepolicy; OWASP's session-management guidance covers these and other session controls (Session Management Cheat Sheet).
Self-contained tokens (JWT)
#A JSON Web Token carries claims (user id, expiry, scopes) and a signature, encoded as three base64url parts separated by dots: header, payload and signature (RFC 7519). Any service with the verification key can check it without a lookup.
- No per-request lookup: good for many services and high request rates.
- Hard to revoke: a stolen token is valid until it expires.
- Signed, not encrypted by default: anyone holding it can read the claims. Do not put secrets in it.
Rules for using JWTs safely, in the spirit of the JWT best-current-practice document (RFC 8725):
- Verify the signature with the expected algorithm only; never accept
noneor let the token choose the algorithm. - Check the claims: issuer (
iss), audience (aud, so a token for one service is not accepted by another), expiry (exp), and not-before (nbf). - Short lifetimes for access tokens (minutes), with refresh tokens (longer-lived, stored securely, rotated on use) to get new ones.
- For immediate revocation needs (account compromise, logout everywhere), keep a small denylist of revoked token ids until they expire, or use sessions.
// Illustration: what token validation must check (library calls vary).Claims claims = verifier .requireAlgorithm("RS256") // never trust the token's own choice .requireIssuer("https://auth.pixly.example") .requireAudience("pixly-api") .clockSkewSeconds(30) .verify(bearerToken); // signature + exp + nbfif (revokedTokenIds.contains(claims.id())) { throw new Unauthorized();}Server-side session | JWT access token | |
|---|---|---|
Lookup per request | Yes (session store) | No |
Revocation | Immediate | Only at expiry, unless you add a denylist |
Works across many services | Needs shared store or gateway translation | Yes, with the public key |
Size | Small cookie | Larger header |
Typical fit | Traditional web apps, admin consoles | APIs, mobile apps, microservices behind a gateway |
A common hybrid: the browser holds a session cookie with the gateway (easy revocation), and the gateway issues short-lived internal tokens to services.
Authorisation: what the caller may do
#Authorisation must answer, for every request: may this identity perform this action on this specific resource?
Models
#- Role-based (RBAC): permissions attached to roles (admin, editor, viewer). Simple; coarse.
- Attribute-based (ABAC): decisions from attributes of the user, resource and context (department, owner, time, region). Flexible; more complex.
- Relationship-based: permissions from relationships (owner, follower, team member), natural for social and collaboration products.
The rules that prevent most breaches
#OWASP's authorisation guidance stresses principles such as least privilege, deny by default, validating permissions on every request, and checking access at the object level (Authorization Cheat Sheet). In architecture terms:
- Check per object, in the service that owns it: "is order 1042 owned by this user, or is the user staff with permission?" The gateway can check "is this a valid user"; only the order service knows who owns order 1042.
- Never trust ids from the client alone: derive the user from the authenticated token, not from a
user_idin the request body. - Check functions: admin endpoints require admin permissions, verified server-side.
- Check properties: do not let clients set fields they should not (a user updating their own
rolethrough a generic update endpoint). - Centralise policy logic in a library or policy service so it is consistent, but enforce it where the data lives.
// Illustration: object-level authorisation in the owning service.Order order = orders.findById(orderId).orElseThrow(NotFound::new);if (order.customerId() != caller.userId() && !caller.hasPermission("orders:read:any")) { throw new NotFound(); // 404 rather than 403, so ids of others' orders are not confirmed}The OWASP API Security Top 10 (2023)
#OWASP's list of the most critical API risks is a useful checklist for any design review (OWASP API Security Top 10 2023):
Risk | Design response |
|---|---|
API1 Broken Object Level Authorization | Per-object ownership checks in the owning service |
API2 Broken Authentication | Proven identity provider, token validation, MFA, login rate limits |
API3 Broken Object Property Level Authorization | Explicit allow-lists of readable and writable fields; separate DTOs |
API4 Unrestricted Resource Consumption | Rate limits, quotas, size limits, pagination caps, timeouts |
API5 Broken Function Level Authorization | Deny by default; server-side permission checks on admin functions |
API6 Unrestricted Access to Sensitive Business Flows | Abuse controls on flows such as sign-ups, ticket purchases, coupon use (bot detection, limits per account) |
API7 Server Side Request Forgery | Validate and restrict server-side fetches of user-supplied URLs |
API8 Security Misconfiguration | Secure defaults, configuration review, automated checks |
API9 Improper Inventory Management | Catalogue every API and version; retire old ones |
API10 Unsafe Consumption of APIs | Treat third-party responses as untrusted input; timeouts and validation |
Service-to-service security
#Inside the system, services call each other. "It is on the internal network, so it is trusted" is the assumption zero trust rejects: NIST's zero-trust architecture guidance describes moving away from implicit trust based on network location towards authenticating and authorising each request (NIST SP 800-207).
- Mutual TLS (mTLS): both sides present certificates, so each service proves its identity and traffic is encrypted. Service meshes can automate this (article 26).
- Workload identities and short-lived credentials instead of long-lived shared passwords.
- Least privilege between services: the notification service may read contact details, not payment data.
- Propagate the end user's identity (for example as a signed internal token) when a downstream service must authorise on the user's behalf.
Encryption
#- In transit: TLS everywhere users connect, and for internal traffic carrying sensitive data (article 03 discussed termination at the load balancer and re-encryption). TLS 1.3 is the current version.
- At rest: enable encryption for databases, disks, backups and object storage. Managed key management services hold keys and support envelope encryption (data is encrypted with a data key, which is itself encrypted by a master key the service guards), rotation and access logging.
- Field-level encryption for especially sensitive fields (government ids, bank details), so even database administrators and backups do not expose them in plain text.
- Hashing is not encryption: passwords are hashed (one-way); data you need to read back is encrypted.
Encryption at rest protects against stolen disks and backups; it does not protect against an attacker who can query your application. Authorisation does that.
Secrets management
#Database passwords, API keys, signing keys and provider credentials are secrets. OWASP's secrets-management guidance covers the essentials: centralise secrets, control and audit access, rotate them, and avoid exposing them in code, logs and build artefacts (Secrets Management Cheat Sheet).
- Never in source code, container images, client apps or logs.
- Store them in a secrets manager (a managed cloud service or a self-hosted vault), fetched at startup or runtime with the service's identity.
- Rotate regularly and immediately after suspected exposure; design so rotation needs no downtime (support two valid credentials during the switch).
- Scan repositories for accidentally committed secrets.
- Configuration that is not secret can live in environment variables or config files, as the Twelve-Factor guidance suggests for configuration in general; secrets deserve the stronger handling above.
Input validation and abuse prevention
#- Validate at the boundary (article 04): types, lengths, ranges, formats; reject early.
- Parameterised queries against SQL injection; output encoding against cross-site scripting in web pages.
- Limits on everything: request size, upload size, page size, query complexity, number of items per batch.
- Rate limits and quotas per user, API key and IP (article 31), plus stricter limits on sensitive flows (login, password reset, sign-up, OTP verification).
- Bot and fraud controls on business flows attackers abuse: ticket purchases, coupon redemption, fake sign-ups.
- Edge protection: a CDN or web application firewall absorbs volumetric attacks and filters known bad patterns before they reach your servers.
- CORS configured narrowly for browser clients; it controls which web origins may call your API from a browser, not who may call it at all.
Server-side request forgery (SSRF)
#Any feature where your server fetches a URL supplied by a user (link previews, "import from URL", webhooks you call) can be abused to make your server request internal addresses: cloud metadata endpoints, admin panels, internal services. OWASP's SSRF prevention guidance recommends approaches such as allow-listing destinations where possible, validating and resolving addresses and blocking private and link-local ranges, disabling redirects or re-validating after them, and isolating the fetching component (SSRF Prevention Cheat Sheet). In a design, run URL fetching in an isolated worker with no access to internal networks.
Privacy and data protection
#- Collect less: do not store data you do not need. Data you do not hold cannot leak.
- Know where personal data lives: classify fields and stores, including logs, caches, analytics, events and backups.
- Retention and deletion: define how long each kind of data is kept, and how a user's data is deleted or anonymised everywhere, including derived stores. Event-sourced and log-based systems need special techniques (article 27).
- Access control and logging for personal data, especially by staff.
- Residency: some regulations require certain data to stay in a country or region, which shapes multi-region design (article 24).
- Regulation: laws such as the EU's GDPR and India's Digital Personal Data Protection Act, 2023 impose obligations on how personal data is collected, used, stored and erased. Requirements and rules change; confirm current obligations with official sources and legal advice for your situation.
Audit logs
#An audit log records security-relevant actions: logins and failures, permission changes, admin actions, data exports, access to sensitive records, configuration changes. It answers "who did what, when, from where".
- Separate from application debug logs, with stricter access and longer retention.
- Append-only and tamper-evident (write-once storage, hash chaining or a separate account).
- Contains identities and actions, not secrets or unnecessary personal data.
- Monitored: alerts on suspicious patterns (mass exports, repeated failures, privilege escalations).
Payments: keep card data out
#The Payment Card Industry Data Security Standard (PCI DSS, currently version 4.x) applies to entities that store, process or transmit cardholder data (PCI DSS). The architectural lesson: avoid touching card data at all where you can. Use a payment provider's hosted payment page or client-side fields that send card details directly to the provider, and store only the provider's tokens and payment references. This greatly reduces the parts of your system in scope for card-security requirements. Article 39 builds on this.
Worked example: securing Pixly
#Area | Decision |
|---|---|
Identity | Authentication through an identity provider with OpenID Connect; MFA available; login rate-limited per account and IP |
Tokens | Short-lived access tokens (10 minutes), validated at the API gateway (signature, issuer, audience, expiry); refresh tokens rotated on use and revocable; denylist for "log out everywhere" |
Authorisation | Each service checks object-level permissions: photo visibility (public, followers-only, private), ownership for edits and deletes, staff permissions for moderation; deny by default |
Edge | TLS at the CDN and gateway; WAF and DDoS protection at the edge; per-user and per-IP rate limits; upload size limits |
Uploads | Presigned URLs with short expiry and fixed keys into a private bucket; files scanned before becoming visible (article 10) |
Service-to-service | mTLS between services; each service has its own identity and least-privilege access to its own data store |
Data at rest | Database, backups and buckets encrypted with managed keys; email addresses and phone numbers in a separate, more restricted table |
Secrets | In a secrets manager; rotated quarterly and on exposure; repository scanning in CI |
Link previews | Fetched by an isolated worker with an egress allow-list and private-range blocking |
Privacy | Account deletion removes or anonymises personal data in the database, caches, search index and analytics within a defined period; backups expire on schedule |
Audit | Moderation actions, staff data access, permission changes and exports written to an append-only audit store with alerts on anomalies |
Threat walk-through
#Threat | Mitigation |
|---|---|
Changing ids in URLs to view private photos | Object-level visibility checks in the photo service; 404 for unauthorised |
Stolen access token | Short expiry; refresh token rotation detects reuse; denylist |
Credential stuffing | Login rate limits, breached-password checks, MFA |
Public bucket misconfiguration | Block public access by default; CDN with restricted origin access; configuration scanning |
Scraping all profiles | Rate limits, pagination caps, bot detection |
SSRF through link previews | Isolated fetcher, allow-list, private-range blocking |
Insider misuse | Least privilege, audit logs with alerts, approvals for sensitive access |
Failure modes
#Failure | Effect | Mitigation |
|---|---|---|
Identity provider outage | Nobody can sign in | Existing tokens keep working until expiry (local validation); multi-zone provider; status messaging |
Signing key compromise | Attackers mint valid tokens | Key rotation with key ids, short token lifetimes, emergency revocation plan |
Revocation needed for JWTs | Stolen tokens valid until expiry | Short lifetimes, denylist, sessions for high-risk apps |
Secret leaked in a repository | Credential abuse | Scanning, immediate rotation, least privilege limits blast radius |
Authorisation check missing on one endpoint | Data exposure | Deny by default, shared policy library, tests for every endpoint |
Logs containing tokens or personal data | Secondary leaks | Redaction, structured logging, reviews |
Trade-offs
#Choice | You gain | You pay |
|---|---|---|
Sessions | Easy revocation | Session-store lookup per request |
JWTs | No lookup, scales across services | Revocation and key-management complexity |
mTLS everywhere | Encrypted, authenticated internal traffic | Certificate management, some latency |
Field-level encryption | Strong protection for sensitive fields | Harder querying, key management |
Strict rate limits | Abuse resistance | Risk of blocking legitimate heavy users |
Identity provider | Proven, maintained authentication | Dependency and cost |
Common mistakes
#- Checking authentication but not per-object authorisation.
- Trusting a user id sent in the request body.
- Long-lived JWTs with no revocation strategy; accepting tokens without checking audience and issuer.
- Secrets in code, environment files in repositories, or logs.
- Treating the internal network as trusted.
- Fetching user-supplied URLs from servers with internal access.
- Storing card numbers instead of provider tokens.
In an interview
#- In the Harden phase, cover: authentication method, token or session choice, object-level authorisation, encryption in transit and at rest, secrets, rate limiting, and one abuse case specific to the problem.
- Use precise words: "authn at the gateway; authz per object in the owning service".
- Mention privacy and audit logging when personal or financial data is involved.
- For payments, say "we never store card data; we use the provider's tokens".
Exercises
#Exercise 1
Find the authorisation bugs
#Review this API and list the security problems:
GET /api/users/{userId}/messages (requires a valid token)PATCH /api/users/{userId} body: {"name": "...", "role": "..."}DELETE /api/admin/users/{userId} (hidden from the app's menu)GET /api/export?format=csv (returns all orders)Exercise 2: Sessions or tokens?
#Choose sessions or JWTs (or a hybrid) and justify:
- An internal admin console used by 40 staff, where access must be revoked instantly when someone leaves.
- A mobile app calling 15 microservices at 50,000 requests per second.
- A banking web app where users must be able to "log out of all devices" immediately.
Exercise 3: Secret rotation
#The database password for an API used by 30 servers must be rotated every 90 days without downtime, and immediately if leaked. Design the process.
Exercise 4: The link preview
#A chat app shows a preview (title and image) when a user pastes a URL. Explain how an attacker could misuse it, and design the feature safely.
Show solutionHide solution
GET /api/users/{userId}/messages: requires a token but probably does not check thatuserIdequals the caller (broken object-level authorisation). Derive the user from the token (/api/me/messages) or check ownership.PATCH /api/users/{userId}withrole: broken object property level authorisation (mass assignment): a user can make themselves admin. Accept only allowed fields per caller; role changes need a separate admin-only endpoint. Also check the caller may edituserId.DELETE /api/admin/users/{userId}"hidden from the menu": hiding is not authorisation (broken function-level authorisation). Require admin permission server-side, deny by default, and audit-log the action.GET /api/export: returns all orders, so a data-exposure and resource-consumption risk. Restrict to authorised roles, scope to what the caller may see, paginate or run as an asynchronous job with limits, and audit-log exports.
Exercise 2
Show solutionHide solution
- Sessions. Few users, low traffic, and instant revocation matters; a session store lookup is cheap at this scale.
- Short-lived JWT access tokens validated locally by each service (or at the gateway), plus rotating refresh tokens. A central session lookup at 50,000 requests per second across 15 services would add latency and a critical dependency.
- A hybrid, or sessions: the browser holds an
HttpOnly,Securesession cookie with the gateway (so "log out everywhere" deletes sessions immediately), and the gateway uses short-lived internal tokens for services. If JWTs are used at the edge, keep them very short-lived and maintain a revocation list checked on each request.
Exercise 3
Show solutionHide solution
- Store the credential in a secrets manager; servers fetch it at startup and re-fetch periodically (or on authentication failure), so no deployment is needed to change it.
- Dual credentials: create a second database user (or second password) with the same permissions. Phase 1: add the new credential to the secrets manager as "next". Phase 2: servers switch to the new credential as they refresh. Phase 3: when metrics show no connections using the old credential, revoke it. Next rotation alternates back.
- Automate the schedule (every 90 days) and alert if rotation fails.
- Emergency path: the same automation run immediately, plus investigation of the leak: audit-log review, scanning where it was exposed, and checking database access logs for misuse.
- Least privilege for the credential limits the damage if it leaks: the API's database user cannot drop tables or read other services' schemas.
Exercise 4
Show solutionHide solution
Misuse: the server fetches whatever URL users paste. An attacker pastes internal addresses (a cloud metadata endpoint, http://localhost:8080/admin, internal service names) and the preview reveals internal data, or the server is used to scan the internal network (SSRF). Other risks: huge responses exhausting memory, slow servers tying up workers, and malicious content in returned images or HTML.
Safe design:
- Fetch in an isolated preview service with no access to internal networks or cloud metadata (network policy and egress through a proxy).
- Validate URLs: allow only
http/https, resolve the hostname and block private, loopback and link-local ranges; re-check after redirects (or disable them); limit to standard ports. - Limits: short timeouts, maximum response size, only parse the beginning of HTML, accept only image content types for thumbnails and re-encode them.
- Cache previews by URL so the same link is fetched once.
- Rate-limit preview requests per user.
- Optionally generate previews on the sender's client instead of the server, which removes server-side SSRF risk (at the cost of revealing the sender's IP to the linked site).
Where to go next
#- Next: The System Design Interview Framework: A Repeatable Method for Any Problem begins the case studies, where every design includes a security section built from this article.
- Later: the rate limiter (article 31) and the payment system (article 39) go deeper on two topics introduced here.
Sources & further reading
- Technology
- Software Engineering
- #APIs
- #backend
- #distributed systems
- #roadmap
- #scalability
- #security
- #system design
- #system design interview
Connected lessons
Linked from 2 guides
Other pages in the library that point here.
Keep reading
More in Technology →Guide · Technology
Start Here: Your Roadmap from Zero to Job-Ready DSA
Guide · Technology
Web Development Roadmap: How to Become a Web Developer From Scratch
Guide · Career
A LinkedIn Profile That Gets Recruiter Messages

