SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • SSL/TLS
  • Encryption at Rest
  • Secrets Management
  • Password Management
  • RBAC
  • SAML
  • OWASP Top 10 and Common Attacks
  • DDoS Attacks and Defenses
  • Web Application Firewall (WAF)
  • Certificates and PKI
  • Multi-Factor Authentication (MFA)
  • Zero Trust
  • Key Management (KMS)
  • Data Privacy and GDPR Basics
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Advanced Security

Web Application Firewall (WAF)

A filter in front of your app that reads HTTP requests and blocks known attack patterns.

⏱ 11 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A Web Application Firewall (WAF) sits in front of a web app and reads every HTTP request. It blocks the ones that look like attacks (SQL injection, XSS, path traversal, bad bots) before they reach your code.

  • It works at layer 7: it understands URLs, headers, cookies and bodies. A network firewall only sees addresses and ports.
  • It decides using rules and scores. Rules are guesses about what is bad, so it will sometimes block good users and miss clever attacks.
  • It is a safety net, not a substitute for secure code. It is also a fast way to patch a hole while the real fix is built.

02Concept: What is it?

A normal firewall asks "is this machine allowed to talk to that port?" A WAF asks "does this request, once I read it, look like an attack?" To do that it must see inside the request, so it sits where TLS has already been removed: on a reverse proxy, on a CDN edge, in a cloud load balancer, or as a module inside the web server.

Each request is checked against a rule set. A widely used free set is the OWASP Core Rule Set. Rules look for suspicious patterns: SQL keywords in a search box, script tags in a form field, ../ in a file name, a known bad user agent. Many WAFs do not block on one match. They add up points (anomaly scoring) and block only when the total passes a limit. A lower limit means more safety and more false alarms.

Where a WAF sits
🌐ClientHTTPS request
→↓TLS
🧱WAFreads and scores it
→↓clean
πŸ–₯️Your appstill validates input
Traffic is decrypted at the edge, inspected, then passed on only if it looks safe.
🧠A WAF guesses
It cannot know your business rules. A request for someone else's order looks exactly like a normal request, so only your code can stop it.

03Real-Life Example

🍡The Mail Room Scanner
A large company has a mail room that opens and scans every parcel before it goes to a desk. It looks for known dangers: powder, wires, suspicious labels. It stops most of them. But it sometimes blocks a harmless parcel that looks odd (false alarm), and a clever sender can hide something in a way the scanner does not know (a miss). The mail room is a helpful layer. The staff at the desks still need to be careful.
Mail room
WAF
A scanner at the company door
A WAF in front of the app
Opening the parcel to look inside
Reading the HTTP request body, headers and URL
A list of known dangerous items
Rules such as the OWASP Core Rule Set
Points for each suspicious sign
Anomaly scoring
A harmless parcel stopped by mistake
False positive
A cleverly hidden danger that passes
False negative (a miss)
A trial period where it logs but does not stop
Detect (log-only) mode

04Why Do We Need It?

🩹Virtual patching
When a new hole is announced, a WAF rule can block the attack in hours, while the real fix takes days.
πŸ”‹Less noise for the app
Obvious scans and exploit attempts are stopped before they use your servers.
πŸ€–Bot control
Block scrapers, credential stuffing and fake sign-ups using rules and reputation.
πŸ•ΈοΈProtect old apps
Legacy systems that cannot be changed still get a layer of protection.
πŸ“ŠVisibility
Logs show what attackers try, which helps you prioritise fixes.
πŸ“œCompliance
Some standards, such as PCI DSS, expect a WAF or regular code review on public web apps.
A WAF buys time and reduces noise. It does not remove the need to fix the code.

05Where Do We Use It?

🌍CDN edge
Cloud CDNs offer a WAF at the edge, so attacks are stopped close to the attacker and far from your servers.
☁️Cloud load balancer
Managed WAF services attach to a load balancer or API gateway with a few clicks.
πŸ”€Reverse proxy
A proxy such as Nginx with a WAF module runs in your own network.
πŸ–₯️Host module
A module inside the web server, such as ModSecurity, inspects traffic on the same machine.
πŸšͺAPI gateway
Gateways apply some of the same checks to APIs: schema checks, size limits, rate rules.
☸️Kubernetes ingress
An ingress controller can run WAF rules for all services behind it.

06Types / Parts / How It Works

What a WAF can do

FeatureWhat it doesExample
Signature rulesMatch known attack patternsSQL keywords with a quote in a query parameter
Anomaly scoringAdd up points from many weak signs, block above a limitOdd header + encoded characters + long value
Allow and deny listsAlways allow or always block certain sources or pathsAllow your office range to /admin, deny a known bad range
Rate rulesLimit requests per client or per pathNo more than 5 logins a minute from one address
Bot managementTell humans from scriptsChallenge pages, reputation, behaviour
Virtual patchingA targeted rule for one known holeBlock the exploit path of a new library bug
Schema checks (for APIs)Reject requests that do not match the API definitionWrong field type, unknown field, huge body

Modes

Roll out a WAF in three steps
1. Detect
πŸ“Log onlynothing is blocked
2. Tune
πŸ”§Fix false alarmsexceptions per path
3. Block
β›”Enforcekeep watching logs
Never turn on blocking first. Learn from your own traffic.
Learn Adjust Protect

Where WAFs struggle

  • Encoding tricks. The same attack written in different encodings (URL, double encoding, mixed case) may slip past a weak rule. Good WAFs normalise the request first.
  • Exposed origin. If an attacker can reach your servers directly, bypassing the WAF's address, the filter is useless. Only accept traffic from the WAF.
  • Business logic. Reusing a coupon, reading another user's record: the request looks fine.
  • Encrypted payloads. If the WAF cannot see inside the request, it cannot check it.
VisualizerSend nine requests through a WAFStart in Block mode and move the sensitivity up and down. Watch real users get blocked at high sensitivity and attacks sneak through at low. Then try Detect mode, and look at the last request: no setting stops it.
WAF mode
GET /products?id=42A normal page viewscore 0allowedreal user ok
POST /login user=aliceA normal loginscore 1allowedreal user ok
GET /search?q=' OR '1'='1Textbook SQL injectionscore 8blockedattack stopped
GET /search?q=<script>alert(1)</script>Script in a search box (XSS)score 9blockedattack stopped
GET /files?name=../../etc/hostsPath traversalscore 7blockedattack stopped
POST /comment I love <b>bold</b> textReal user using HTML tagsscore 4allowedreal user ok
POST /forum How do I use SELECT * FROM in SQL?Real user asking about SQLscore 6blockedfalse alarm
GET /search?q=%27%20OR%20%271%27%3D%271The same SQL trick, URL-encoded to hidescore 3allowedattack got in
GET /orders/1002 (someone else's order)Broken access control: looks like a normal requestscore 0allowedattack got in
Attacks stopped
3 / 5
Attacks reached app
2
missed
Real users blocked
1
false positives
Alerts logged
4
Both problems at once: 1 real user(s) were blocked and 2 attack(s) still got through. No sensitivity setting fixes both, because the WAF only guesses from patterns.

The scores are made up for the demo and fixed, so the page looks the same every time. Real WAFs add up points from many rules (for example the OWASP Core Rule Set) and block when the total passes a limit.

07How to Use It / Steps / Implementation

Adding a WAF safely

  1. 1
    Put it where TLS ends
    The WAF must be able to read requests. Terminate TLS at the edge or the proxy, and keep traffic after that private.
  2. 2
    Start in detect mode
    Log what it would block for a week or two of real traffic.
  3. 3
    Review the logs
    Find false positives (real users flagged) and add narrow exceptions for specific paths or fields.
  4. 4
    Switch to blocking
    Move to blocking in stages, for example one path or one percent of traffic first.
  5. 5
    Lock down the origin
    Allow only the WAF to reach your servers, using network rules or a shared header or mutual TLS.
  6. 6
    Add rate and bot rules
    Protect login, sign-up and search from scripted abuse.
  7. 7
    Keep tuning
    Update rule sets, review alerts, and re-test after every big release.
πŸ’‘Use it as a fast patch
When a library bug is announced, add a narrow WAF rule for the exploit path the same day, then ship the real upgrade. Remove the rule when it is no longer needed.
⚠️Do not skip secure code
A WAF can be bypassed. Keep input validation, parameterized queries and authorization checks in the app. Link: Input Validation.

08Key Terms to Know

TermMeaning in easy words
WAFWeb Application Firewall: a layer 7 filter in front of a web app
Layer 7The application layer, where HTTP lives
Rule setA bundle of rules, such as the OWASP Core Rule Set
Anomaly scoringAdding points for suspicious signs and blocking above a limit
False positiveA legitimate request that is blocked by mistake
False negativeAn attack that is not caught
Detect modeThe WAF logs what it would block, but lets traffic through
Virtual patchingA WAF rule that blocks an exploit until the code is fixed
NormalisationDecoding and cleaning a request so tricks in encoding do not hide an attack
OriginYour real servers behind the WAF
Bot managementTelling real users from automated scripts
ModSecurityA well-known open source WAF engine

09Pros, Cons and Trade-offs

βœ… Pros
  • Blocks many common attacks automatically
  • Fast response to new vulnerabilities (virtual patching)
  • Protects apps you cannot change quickly
  • Adds bot and rate controls
  • Gives useful attack visibility
⚠️ Cons
  • False positives block real users
  • Can be bypassed by new or encoded attacks
  • Cannot see business logic flaws
  • Needs tuning and ongoing care
  • Adds latency and cost, and a new thing to fail

Trade-offs

ChoiceWe gainWe lose
High sensitivityMore attacks caughtMore real users blocked
Low sensitivitySmooth experienceMore attacks reach the app
Block modeReal protectionMistakes are visible to users
Detect modeSafe learningNo protection yet
Managed cloud WAFEasy setup, updated rulesLess control, per-request cost
Self-hosted WAFFull controlYou tune and update everything

10Common Problems and Mistakes

Common mistakes

  1. Turning on blocking on day one. Real customers get blocked and the team switches the WAF off.
  2. Leaving the origin open. Attackers go straight to the server address and skip the WAF.
  3. Believing the WAF fixes bugs. The hole is still there. It is only harder to reach.
  4. Never reviewing logs. Alerts that no one reads protect nothing.
  5. Global exceptions. Disabling a rule everywhere because of one noisy form. Make exceptions narrow.
  6. Forgetting APIs. JSON bodies and mobile clients need their own rules and checks.
  7. Not testing after changes. A new field or endpoint can start triggering rules.

Things to watch

πŸ“Body size limits
Large uploads may be skipped or blocked. Know what your WAF inspects.
⏱️Latency
Inspection adds time. Measure it on your slowest paths.
πŸ”ŒSingle point of failure
If the WAF is down, the site may be down. Run it with redundancy.
πŸ”’Sensitive data in logs
WAF logs may capture form fields. Mask passwords and personal data.

11Real-World Examples

🌍CDN-based WAFs
Large CDN providers sell a WAF that runs at the edge, which also helps absorb floods of traffic.
☁️Cloud-native WAFs
The big cloud providers each offer a managed WAF that attaches to their load balancers and gateways.
πŸ› οΈModSecurity
A long-standing open source engine, often used with the OWASP Core Rule Set.
🩹Log4Shell response
When the Log4j flaw was announced in late 2021, many teams used WAF rules as an emergency shield before they could upgrade.
🏦Regulated industries
Payment and healthcare systems commonly put a WAF in front of public portals.
πŸ€–Login protection
Retail sites use bot rules and rate limits to blunt credential stuffing.
Mini case: emergency patch
πŸ“£New hole announcedexploit in the wild
→↓hours
🧱WAF rule addedblocks the exploit path
→↓days
βœ…Code upgradedrule removed later
A rule buys the team a few days to ship the proper fix.

12Related Topics to Read Next

Firewalls and VPN→

The network layer firewall, and the one right below the WAF.

Input Validation→

The in-app defence a WAF must never replace.

OWASP Top 10 and Common Attacks→

The attacks a WAF is built to block.

API Gateway Pattern→

A front door that also applies limits and checks.

DDoS Attacks and Defenses→

Floods of traffic, which a WAF and CDN help absorb.

Rate Limiting→

The rate rules inside a WAF work the same way.

SSL/TLS→

Where TLS ends decides where the WAF can read.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”WAF: a layer 7 filter that reads HTTP requests and blocks attack patterns.
  • βœ”Placement: CDN edge, load balancer, reverse proxy or host module, after TLS ends.
  • βœ”Decides by: rules (for example the OWASP Core Rule Set) and anomaly scores.
  • βœ”Rollout: detect, tune, then block.
  • βœ”Strength: virtual patching, bot and rate rules, visibility.
  • βœ”Weakness: false positives, evasion, business logic flaws, exposed origin.
  • βœ”Rule: a WAF is a layer, never a replacement for secure code.
  • βœ”One line: β€œA mail-room scanner for web requests: useful, imperfect, and never the only guard.”
← Previous
DDoS Attacks and Defenses
Next β†’
Certificates and PKI