Backend Development
2 min read
Validate UUID Values Before Writing Them to a Database
A practical UUID validation workflow for APIs, database writes, logs, and tests that separates shape checks from real authorization.
UUIDs are often treated as harmless strings, yet an invalid identifier can trigger confusing database errors, cache misses, or broad fallback queries. Validate shape early, but do not confuse a well-formed UUID with an authorized or existing resource. Input validation should reject malformed data; the service layer must still enforce ownership and record existence.
## Check the shape at the boundary
An RFC 4122 UUID is commonly written as 36 characters: eight hexadecimal digits, then groups of four, four, four, and twelve separated by hyphens. A validator can also identify the version and variant fields. This catches a copied id with a missing character, an accidental newline, or an identifier from another format before it reaches a query builder.
The CalcSnippets UUID Validator checks multiple values locally and reports valid shapes. Use it when reviewing a log sample or fixture, then add the equivalent validation in the API boundary. Keep the error message specific enough for a client to correct its request without echoing an unrelated identifier back to an unauthorized caller.
## Preserve semantics after validation
Do not convert all identifiers to UUID just because the column can store them. A human account code or an external provider id may have leading zeros or meaningful prefixes. If the system expects a UUID, store it in a native UUID type where the database supports one. That gives queries, indexes, and drivers a consistent representation.
Validation does not tell you whether a UUID was generated securely. For sensitive tokens, do not use a predictable counter disguised as an identifier. Use a cryptographically secure UUID generator or a purpose-built token mechanism. For database primary keys, consider index locality and operational requirements as well as uniqueness.
## Test failure paths deliberately
Include malformed ids, a valid id for another tenant, a deleted record, and a valid current record in endpoint tests. Those cases prove that validation, lookup, and authorization remain separate. Log a request correlation id rather than the full customer identifier where privacy policy requires it. A small amount of disciplined identifier handling prevents a common class of confusing production failures.