Validate at the edge
Injection, oversized payloads and malformed input reach business logic.
Say it like this
Nothing from outside is trusted, so I validate shape, size and type at the API boundary, pass data to the database only through parameterised queries, and reject early with a 400 before any business logic runs.
Basic solution
Validate schema, size and type at the API boundary; use parameterised queries; reject early with 400.
Cheap checks first, data as data at the store
The edge rejects oversized and malformed traffic before it is read; the service validates against a schema and semantics; the database only ever sees bound parameters; output is encoded for the context it is rendered in.
How it works
- The edge (gateway or reverse proxy) enforces coarse limits before anything else: maximum request size, header count, allowed content types, and a web application firewall rule set for known-bad patterns. A body over the size limit is rejected before it is even read into memory.
- The service parses the body against a declared schema: required fields, types, string lengths, allowed enum values, number ranges and array sizes. Fields not in the schema are rejected or stripped, depending on what the API contract promises.
- Semantic checks follow, meaning rules about what the values mean rather than their shape: the URL to shorten must be http or https and must not point at an internal address; the template may only reference variables it declared; the phone number must be in E.164 format.
- Data reaches the database only through parameterised queries or an ORM that binds values, which sends the query text and the values to the database separately so content is never interpreted as SQL. The same rule applies to shell commands, LDAP queries and templating engines: data is data.
- Output encoding covers the other direction. User content rendered into HTML, an email or a template is escaped for that specific context, so a name containing angle brackets displays as text rather than running as markup.
Order matters
- Cheap checks first (size, type), expensive ones last (lookups, external calls). An attacker should not be able to make you do real work before the request has proven it is well-formed.
Worked example
Notification system
- POST /v1/notifications carries templateId, variables (a JSON object), userId, priority, channels. Schema: priority is one of two enums, channels is an array of at most 3 known strings, variables has at most 20 keys of at most 1 KB each, total body at most 64 KB.
- At 2,900 requests/s, schema validation of a 2 KB body costs about 30 microseconds with a compiled JSON Schema validator: 0.09 CPU-seconds per second, nothing.
- Template rendering: the template engine runs in a sandbox with no file or network access, and variables are inserted with HTML escaping for email and plain insertion for SMS. A variable like a name is never interpreted as template syntax.
- Device token registration: tokens are validated against the provider's format (64 hex characters for APNs) so junk never reaches the provider, which would otherwise count towards rate limits and error quotas.
- Size limit at the edge: a 10 MB body is rejected by nginx before the service allocates anything. Without that limit, 1,000 concurrent 10 MB uploads is 10 GB of memory in workers.
- Rejection rate in practice: well under 1% of traffic, but each rejection is a 400 served in under a millisecond instead of a 500 after a crashed worker.
Variants and when each wins
Schema validation at the boundary
- JSON Schema, Protobuf or a typed framework (Pydantic, zod) checks every request against a declared contract. It wins by catching shape and type errors in one place, keeping business code free of defensive checks.
WAF rules at the edge
- Pattern rules for injection attempts, oversized headers and known-bad user agents run before any service. It wins because it is cheap and protects every service at once; it is noisy and never a substitute for parameterised queries.
Allow lists over deny lists
- Validation defines what is valid (these enum values, this character set, this length) rather than what is forbidden. It wins because a deny list always misses a variant nobody thought of.
Validation in the client only
- The app checks input before sending it. It improves the user experience and provides no security at all, because anyone can call the API directly; always repeat the checks on the server.
Recommendation: edge size limits and a WAF, schema validation in the service with allow lists, parameterised access to every store, and context-aware output encoding.
Failure modes
Injection through string concatenation
- A crafted input changes what a query does. It happens because SQL or a shell command was built by joining strings that included user input. Use parameterised queries everywhere, add a lint rule that rejects string-built SQL, and give the database account the least privilege it needs so even a bug cannot drop tables.
Resource exhaustion from oversized input
- Workers run out of memory or spend seconds parsing one request. It happens because there was no limit on body size, array length or JSON nesting depth. Enforce limits at the edge and in the parser: maximum body, maximum array length, maximum nesting.
Server-side request forgery via a user-supplied URL
- The shortener's link-preview fetcher reaches an internal metadata endpoint and returns credentials. It happens because the service fetched whatever URL the user supplied. Resolve the host first, reject private and link-local address ranges, apply the same check to every redirect, and fetch from an isolated network.
Validation drift between client and server
- The app blocks an input the API accepts, or the other way round. It happens because the client and server have two hand-written rule sets. Generate the client-side validation from the same schema the server uses (OpenAPI, Protobuf).
Error messages that leak
- A 400 response echoes a stack trace or a fragment of the query. It happens because the framework's default error handler was never replaced. Return structured error bodies with a code and the field path, and keep the details in server logs.
Interviewer follow-ups
Answer out loud before you open each one.
Where exactly should validation happen in a system with a gateway and many services?
Size, rate and coarse pattern checks at the gateway, because they protect every service and need no business knowledge. Schema and semantic validation in each service, because only the service knows its contract. Services should not trust each other either; internal callers get the same schema check.
Why is a parameterised query safer than escaping the input?
Parameters are sent to the database separately from the query text, so the database never parses them as SQL regardless of content. Escaping tries to make data safe inside the text and has to be correct for every database dialect and encoding, which it historically has not been.
How would you validate a user-supplied URL in the shortener?
Parse it with a real URL parser, allow only http and https, cap the length at 2 KB, and reject hosts that resolve to private, loopback or link-local addresses if the system ever fetches it. Optionally check it against a malware list asynchronously and quarantine rather than block the create call.
What is the difference between validation and sanitisation?
Validation rejects input that does not meet the contract; sanitisation alters it to make it acceptable. Prefer validation: it keeps data faithful and the rules explicit. Sanitise only where altering is the product behaviour, like stripping unsupported HTML from a comment, and encode on output regardless.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| AWS WAF | Gateway / WAF | Cloud Armor | Azure Web Application Firewall | Cloudflare WAF, ModSecurity |
| Amazon EC2 Auto Scaling | Notification API, Template renderer | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Aurora | Database | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |