Security is not a feature that we add after designing a system.
Security is an architectural property.
A system can be:
and still be a failure if an attacker can:
A secure system therefore considers security at every layer:
User
|
v
DNS / Edge
|
v
Load Balancer
|
v
API Gateway
|
v
Application
|
+---- Authentication
|
+---- Authorization
|
v
Database
|
v
StorageSecurity must exist across all of these boundaries.
Before designing security, identify assets.
Typical assets include:
Security design starts with:
What are the assets, who can access them, and what happens if they are compromised?
A foundational security model is the CIA triad.
Security
/ \
/ \
Confidentiality Integrity
\ /
\ /
AvailabilityOnly authorized users should access data.
Example:
User A
X
|
User B's private messagesData should not be modified improperly.
Example:
Payment = ₹1,000An attacker must not be able to change it to:
Payment = ₹1Authorized users should be able to use the system when needed.
Examples:
Security therefore overlaps with the availability topics from previous chapters.
This is one of the most important distinctions.
Authentication asks:
Who are you?
Examples:
Authorization asks:
What are you allowed to do?
Example:
User
|
+---- Read own profile
|
+---- Edit own profile
|
X---- Delete another user's accountAuthentication without authorization is dangerous.
A user may successfully log in but still not have permission to access every resource.
Identity represents an entity interacting with the system.
Examples:
A useful model is:
Identity
|
v
Authentication
|
v
Authorization
|
v
ResourceGive an identity only the permissions it needs.
Bad:
Application
|
v
Database AdminBetter:
Application
|
v
Limited DB User
|
+---- SELECT
+---- INSERT
+---- UPDATEThe application should not automatically have permissions such as:
DROP DATABASE
CREATE USER
ALTER SYSTEMLeast privilege reduces blast radius.
Do not rely on a single security mechanism.
Example:
WAF
|
TLS
|
Authentication
|
Authorization
|
Input Validation
|
Rate Limiting
|
Database Permissions
|
Encryption
|
MonitoringIf one control fails, another control may still reduce the impact.
This is called:
Defense in depth.
A security boundary is a point where trust changes.
Example:
Internet
|
| untrusted
v
API Gateway
|
| authenticated
v
Application
|
| restricted
v
DatabaseDo not assume that an internal network automatically means trusted.
A compromised service inside the network may still attack another service.
A simplified zero-trust principle is:
Do not automatically trust a request simply because it comes from inside the network.
Instead:
Request
|
v
Authenticate
|
v
Authorize
|
v
Validate
|
v
Access ResourceThis is especially important in:
Never store passwords as plain text.
Bad:
username: anubhav
password: MyPassword123If the database is compromised, the password is immediately exposed.
Instead:
Password
|
v
Password Hash Function
|
v
Stored HashModern password hashing should use algorithms designed specifically for password storage, such as:
A general-purpose fast hash such as SHA-256 is not by itself a suitable password-storage strategy.
A salt is a unique random value used with password hashing.
Conceptually:
Password + Salt
|
v
Password HashDifferent users with the same password should not end up with identical stored hashes.
Example:
User A:
password + saltA -> hashA
User B:
password + saltB -> hashBThe server should not decrypt a password.
Instead:
User enters password
|
v
Hash using stored salt/configuration
|
v
Compare with stored password hash
|
/ \
match mismatch
| |
login rejectPasswords are generally stored in a one-way password hashing representation.
MFA requires more than one authentication factor.
Common categories include:
Conceptually:
Password
+
Second Factor
|
v
AuthenticatedMFA significantly reduces the impact of stolen passwords.
After authentication, a web application needs to remember the authenticated state.
One common model is a server-side session.
Browser
|
| login
v
Server
|
v
Session StoreThe server creates:
session_id = abc123The browser receives a cookie containing the session identifier.
Subsequent requests send the cookie.
Browser
|
Cookie: session_id=abc123
|
v
Server
|
v
Session StoreAuthentication cookies should normally be protected using appropriate cookie attributes.
Important attributes include:
SecureHttpOnlySameSiteCookie should be sent over HTTPS.
JavaScript cannot directly access the cookie through normal browser APIs.
This can reduce the impact of some XSS-based token theft scenarios.
Controls cross-site cookie behavior and helps mitigate certain CSRF scenarios.
Another model is token-based authentication.
Login
|
v
Authentication Server
|
v
Access Token
|
v
Client
|
v
APIThe client sends the token with requests.
Common formats include JWT, although opaque tokens are also widely used.
JWT stands for:
JSON Web Token
A JWT commonly contains:
Header.Payload.SignatureConceptually:
Header
+
Payload
+
SignatureA payload may contain claims such as:
{
"sub": "user123",
"role": "user",
"exp": 1790000000
}The exact claims depend on the application.
A common misconception:
"JWT hides the data."
A normal signed JWT is not automatically encrypted.
Its payload can generally be decoded by the client.
The signature provides integrity/authenticity properties when correctly validated.
Therefore do not place sensitive secrets inside an ordinary JWT payload.
A server receiving a JWT should verify appropriate properties such as:
Conceptually:
Request
|
v
Extract token
|
v
Verify signature
|
v
Validate claims
|
v
Authorize requestA common architecture uses:
Short-lived Access Token
+
Longer-lived Refresh TokenExample:
Access token:
15 minutes
Refresh token:
days/weeks depending on risk and designThe access token is used frequently.
The refresh token is used to obtain a new access token.
Shorter access-token lifetime can reduce the window of impact if an access token is stolen.
JWTs can introduce a revocation challenge.
If a self-contained access token remains valid until expiration, simply deleting a server-side session does not necessarily invalidate it.
Strategies include:
The correct choice depends on the security and operational requirements.
OAuth 2.0 is an authorization framework.
It allows a client application to obtain delegated access to resources.
Example:
User
|
v
Client Application
|
v
Authorization Server
|
v
Access Token
|
v
Resource ServerA key idea is:
The client does not need the user's password to access the authorized resource.
OpenID Connect (OIDC) adds an identity layer on top of OAuth 2.0.
OAuth primarily concerns delegated authorization.
OIDC provides standardized authentication information.
Simplified:
OAuth 2.0
|
Authorization
OIDC
|
Authentication / IdentityThis distinction is important in system design interviews.
APIs may authenticate clients using:
Choice depends on the client type and threat model.
For example:
Public browser app
-> session/OIDC/OAuth
Service-to-service
-> workload identity / OAuth / mTLS
Simple internal integration
-> API key may be possible, with strong controlsAn API key is a credential identifying a client or application.
Example:
Authorization: Bearer <credential>API keys should be:
Never commit production API keys to source control.
Several authorization models are common.
RBAC:
User
|
+---- Role: ADMIN
|
+---- CREATE
+---- READ
+---- UPDATE
+---- DELETEABAC considers attributes.
Example:
user.department == "finance"
AND
resource.region == user.regionThen access may be allowed.
Access depends on relationships.
Example:
User
|
+---- owns ----> DocumentThe owner may edit the document.
This model is useful in collaboration and social systems.
Always authorize access to the specific resource.
Bad:
GET /users/123/profile
Authentication:
valid
Therefore:
allowThis is insufficient.
The server must also ask:
Is this authenticated user allowed to access user 123?Otherwise the application may have an insecure direct object reference style vulnerability.
In a multi-tenant SaaS system:
Tenant A
|
+---- Users
+---- Orders
Tenant B
|
+---- Users
+---- OrdersA major security requirement is preventing:
Tenant A
X
|
Tenant B dataAuthorization must include tenant context.
Database isolation strategies may include:
Never assume input is safe.
Validate:
Example:
age = "hello"should not be accepted when the API requires an integer.
Validation should happen server-side even if the frontend validates the same field.
SQL injection occurs when untrusted input changes SQL semantics.
Dangerous pattern:
"SELECT * FROM users WHERE name = '" + input + "'"Use parameterized queries instead.
Conceptually:
SQL template
+
Parameters
|
v
DatabaseThe database should treat user input as data rather than SQL syntax.
NoSQL systems can also be vulnerable when untrusted input is interpreted as query operators or expressions.
The same principle applies:
Treat external input as data, not executable query logic.
Use appropriate driver APIs, validation, allowlists, and query construction mechanisms.
XSS occurs when attacker-controlled content is executed in a victim's browser.
Conceptually:
Attacker input
|
v
Application
|
v
Browser
|
v
Malicious script executesDefenses include:
CSRF abuses a victim's authenticated browser context to trigger unwanted actions.
Example:
Victim logged into bank
|
v
Malicious website
|
v
Forged request
|
v
BankCommon defenses include:
CORS stands for:
Cross-Origin Resource Sharing
It controls which browser origins may access resources through browser cross-origin mechanisms.
Example:
https://app.example.commay be allowed to call:
https://api.example.comA common mistake is:
Access-Control-Allow-Origin: *without considering whether the API exposes sensitive authenticated functionality.
CORS is a browser security mechanism; it is not a replacement for authentication or authorization.
HTTP without encryption exposes traffic to network observers.
HTTPS uses TLS.
Conceptually:
Client
|
| encrypted connection
v
ServerTLS provides important protections including:
Modern production systems should use HTTPS for sensitive traffic and generally for web traffic overall.
Data stored on disks or storage systems should be protected appropriately.
Examples:
Conceptually:
Plain Data
|
Encryption
|
v
Ciphertext
|
StorageData moving between components should be protected.
Example:
Client
|
TLS
v
API
|
TLS
v
Service
|
TLS
v
DatabaseInternal traffic should not automatically be considered safe merely because it stays inside a private network.
Encryption is only as strong as key management.
Keys should be:
Avoid embedding encryption keys directly into source code.
A dedicated key-management system or cloud KMS is commonly used.
Secrets include:
Bad:
const API_KEY = "production-secret";Better:
Application
|
v
Secret Manager
|
v
Runtime SecretSecrets should not be committed to Git.
A secret should not necessarily live forever.
A rotation model:
Secret A
|
v
Issue Secret B
|
v
Update consumers
|
v
Validate
|
v
Revoke Secret ARotation reduces the lifetime of compromised credentials.
Rate limiting controls request volume.
Example:
100 requests / minute / userIt can help against:
A distributed system may implement rate limiting using:
Distributed Denial of Service attacks attempt to overwhelm resources.
Possible layers of defense:
Internet
|
v
DDoS Protection
|
v
CDN / Edge
|
v
WAF
|
v
Load Balancer
|
v
ApplicationSecurity architecture should attempt to stop expensive traffic before it reaches expensive backend resources.
WAF stands for:
Web Application Firewall
A WAF can inspect HTTP traffic and apply rules against common web attack patterns.
Conceptually:
Request
|
v
WAF
/ \
allow blockWAF is an additional security layer, not a replacement for secure application code.
Separate systems according to trust and exposure.
Example:
Internet
|
Public Subnet
|
Load Balancer
|
Private Application Network
|
Private Database NetworkThe database should generally not be directly exposed to the public Internet.
Network controls can restrict:
Example:
Internet
|
X----> Database:5432while allowing:
Application
|
+----> Database:5432This limits attack paths.
In microservices:
Service A
|
v
Service BDo not assume Service A is trustworthy forever.
Possible controls include:
mTLS means mutual TLS authentication.
Normal TLS:
Client -> verifies ServermTLS:
Client <-> ServerBoth sides authenticate using certificates.
This is useful for:
Threat modeling asks:
How could this system be attacked?
A useful process:
1. Identify assets
2. Identify trust boundaries
3. Identify attackers
4. Identify attack paths
5. Identify vulnerabilities
6. Identify mitigations
7. Validate controlsA common threat-modeling framework is STRIDE.
| Letter | Threat |
|---|---|
| S | Spoofing |
| T | Tampering |
| R | Repudiation |
| I | Information Disclosure |
| D | Denial of Service |
| E | Elevation of Privilege |
Example:
Login APIAsk:
Security-relevant actions should be observable.
Examples:
Logs should avoid exposing sensitive secrets.
Bad:
password=secret123Better:
user_login_failed
user_id=123
reason=invalid_credentialsAn audit log records important security or business actions.
Example:
2026-10-01
user=123
action=DELETE_ACCOUNT
resource=456
result=DENIEDAudit logs are useful for:
They should be protected against unauthorized modification.
Security monitoring can detect patterns such as:
100 failed logins
|
v
Possible brute forceor:
Normal API usage
|
v
Sudden massive export
|
v
Potential account compromiseMonitoring should combine technical and business signals.
Authentication endpoints are high-value targets.
Controls can include:
A naive permanent lockout can itself be abused to deny legitimate users access.
Session identifiers should be:
Important events may trigger session invalidation:
File uploads create several risks.
Potential problems:
A secure upload architecture may be:
Client
|
v
Upload Service
|
v
Object Storage
|
v
Malware / Content Scan
|
v
Approved StorageDo not blindly trust a filename or MIME type supplied by the client.
SSRF stands for:
Server-Side Request Forgery
It occurs when an attacker can influence the server to make unintended outbound requests.
Example:
Attacker
|
v
Application
|
v
Internal ServicePossible defenses:
Path traversal attempts to access files outside the intended directory.
Example concept:
/download?file=../../secret.txtDefenses include:
Applications depend on:
A compromised dependency can become a production security issue.
Important controls include:
For containerized applications:
Source
|
v
Build
|
v
Container Image
|
v
Registry
|
v
ProductionSecurity should consider:
Kubernetes security includes:
A dangerous pattern is giving workloads excessive permissions.
For example:
Application Pod
|
v
Cluster AdministratorA compromised application could then have an enormous blast radius.
Blast radius describes how much damage can occur after one component is compromised.
Bad:
One compromised service
|
v
Entire database
|
v
Entire platformBetter:
Compromised Service
|
v
Limited permissions
|
v
Small affected scopeLeast privilege, segmentation, and separate credentials reduce blast radius.
Consider an e-commerce system.
Internet
|
v
DDoS Protection
|
v
CDN
|
v
WAF
|
v
Load Balancer
|
v
API Gateway
|
+----------+----------+
| |
v v
User Service Order Service
| |
+----------+----------+
|
v
Authorization
|
+---------+---------+
| |
v v
Database Message Queue
|
v
Encrypted StorageSecurity layers include:
A request can pass through multiple controls:
Client
|
v
TLS
|
v
DDoS Protection
|
v
WAF
|
v
Rate Limiter
|
v
Authentication
|
v
Authorization
|
v
Input Validation
|
v
Business Logic
|
v
Database Authorization
|
v
Audit LogThis is defense in depth.
A typical modern architecture:
+--------------------+
| Identity Provider |
+---------+----------+
|
Authenticate
|
v
Client ----------------> API
|
Access Token
|
v
Authorization
|
v
ResourceThe identity provider can centralize authentication while applications enforce authorization.
Question:
"The user has a valid JWT. Should we allow the request?"
Answer:
Not necessarily.
The JWT may prove identity or carry claims, but the server must still determine whether the user has permission for the specific operation and resource.
Correct flow:
Authentication
|
v
Identity
|
v
Authorization
|
v
Resource AccessSecurity becomes more complicated as the number of components increases.
Monolith:
Client
|
v
Application
|
v
DBMicroservices:
Client
|
API Gateway
|
+---- Service A
|
+---- Service B
|
+---- Service C
|
+---- Service DNow there are many:
Therefore security must be designed as a system-wide architecture.
Security controls can affect:
Example:
mTLSmay improve service identity security but introduce certificate management complexity.
Another example:
Very short token lifetimemay reduce token exposure but increase refresh operations.
System design requires balancing security with operational requirements.
Authentication without authorization.
Storing passwords in plaintext.
Putting secrets in Git.
Trusting internal network traffic automatically.
Using administrator credentials from applications.
Returning sensitive information in logs.
Relying only on a WAF.
No rate limiting on authentication endpoints.
Ignoring tenant isolation.
No audit trail for privileged operations.
Assuming JWT payloads are encrypted.
Using * CORS configuration without understanding the security implications.
When designing a system, use this sequence:
1. Identify assets
|
v
2. Identify users and services
|
v
3. Identify trust boundaries
|
v
4. Identify threats
|
v
5. Design authentication
|
v
6. Design authorization
|
v
7. Protect data
|
v
8. Protect network
|
v
9. Reduce blast radius
|
v
10. Add monitoring/auditing
|
v
11. Test security controlsAuthentication verifies identity.
Authorization determines what an authenticated identity is allowed to do.
Confidentiality, Integrity, Availability.
Granting only the permissions required to perform a task.
To avoid storing recoverable plaintext passwords and reduce the impact of database compromise.
Sessions commonly store server-side state identified by a session cookie. JWT-based authentication can carry signed claims in the token and may reduce server-side session lookup, but introduces token lifecycle and revocation considerations.
An authorization framework for delegated access.
An identity/authentication layer built on OAuth 2.0.
An attack where a victim's authenticated browser context is abused to perform an unwanted action.
Injection of attacker-controlled script/content into a context where it executes in a victim's browser.
Discuss:
Discuss:
Use:
Possible mechanisms:
Discuss:
Global edge
|
Load balancing
|
Authentication service
|
Identity store
|
Token/session infrastructureThen consider:
Design security for:
POST /orders
GET /orders/:id
POST /payments
GET /users/:idRequirements:
Design:
Client
|
v
TLS
|
v
WAF
|
v
Rate Limiter
|
v
API Gateway
|
v
Authentication
|
v
Authorization
|
v
Application
|
v
DatabaseAnswer:
Think about security as multiple questions.
WHO ARE YOU?
|
v
Authentication
|
v
WHAT CAN YOU DO?
|
v
Authorization
|
v
WHAT DATA CAN YOU ACCESS?
|
v
Resource / Tenant Isolation
|
v
HOW IS DATA PROTECTED?
|
v
Encryption
|
v
HOW DO WE LIMIT DAMAGE?
|
v
Least Privilege + Segmentation
|
v
HOW DO WE DETECT ATTACKS?
|
v
Logging + Monitoring
|
v
HOW DO WE RECOVER?
|
v
Incident Response + DRThis connects security with the previous chapters on availability, fault tolerance, and disaster recovery.
In this chapter we learned:
The central principle is:
Security is not one component. It is a layered system of identity, authorization, isolation, encryption, validation, monitoring, and recovery.
Explain:
Authentication
Authorization
Accounting/Auditingand give one example of each.
Design authentication for a consumer application with 50 million users.
Design authorization for a multi-tenant SaaS platform.
Explain how an attacker could move from:
Compromised Service Ato:
Databaseand design controls to prevent it.
Threat-model a payment API using STRIDE.
Design a secure service-to-service architecture using mTLS.
Chapter 30 established the security fundamentals.
The next chapter will go deeper into security architecture for distributed systems, including:
Mark it as complete to track your mastery.