Free APIs come with a lot of challenges.
One of the biggest ones is API key validation.
If done poorly, it can lead to:
performance bottlenecks
unnecessary database load
potential security issues
Here’s how I approached this problem.
Authorization and API Key Design
I didn’t want to validate every API key with a database query.
So I made the key self-contained.
Example:
Authorization: PetProjects ppk_v1_1_nonce_signature
Key format:
ppk_version_userId_nonce_signature
Where:
version — key version
userId — user identifier
nonce — random value
signature — HMAC signature
Validation Flow
The validation process is split into two steps.
1. Fast Validation (No Database)
First, the key is validated locally:
structure check
data correctness
HMAC signature verification
This allows us to reject invalid or garbage keys without touching the database.
2. User Check
If the key is valid:
we extract userId
then perform a single database query
Validation Code
function validateApiKey(apiKey: string): ApiKeyPayload | null
if (!apiKey.startsWith('ppk_')) return null;
const parts = apiKey.split('_');
if (parts.length !== 5) return null;
const [, version, userIdRaw, nonce, signature] = parts;
const userId = Number(userIdRaw);
if (!Number.isInteger(userId)) return null;
if (!signature
Caching
After successful validation, the user is cached:
export const apiKeyCache = new LRUCache(
max: 10000,
ttl: 5 * 60 * 1000,
);
Benefits:
no database hit on every request
reduced latency
lower database load
Why TTL = 5 Minutes
The TTL is intentionally short.
If a key leaks:
it only works for a limited time
then requires revalidation via database
This is a trade-off between performance and security.
Final Thoughts
Don’t validate API keys with a database on every request.
Design them to be verifiable locally.
If you're building a free API, this approach can significantly reduce load while keeping things simple.
Example
I’m using this approach in a free API platform I’m building:
https://pet-projects.io/en/apis
Tags:
#0
Want to run a more efficient business?
Mewayz gives you CRM, HR, Accounting, Projects & eCommerce — all in one workspace. 14-day free trial, no credit card needed.
Try Mewayz Free →