Hashing Passwords in 10 ms of CPU

A Problem I Didn't See Coming
Casual Kitchen Express (CKE) is a food delivery platform I built as a portfolio concept: three Android apps, an API on Cloudflare Workers, and a Postgres database, all on free plans. Payments are simulated. In the first post in this series, I wrote about how free-plan limits shaped the whole architecture. This post zooms in on one of those limits, because it caught me by surprise and the fix taught me more about password hashing than anything I'd read before.
The surprise was this: Cloudflare Workers' free plan gives each request about 10 milliseconds of CPU time, and a normal password hash takes several times that.
Most people in CKE never touch a password. Customers and managers sign in with Google. But riders, kitchen staff, dispatch officers, and account officers get a username and a password from their manager. Their manager creates the account, sets the first password, and resets it when someone forgets. Those passwords have to be stored safely, and on Workers, "safely" ran straight into the CPU limit.
Why Password Hashing Is Meant to Be Slow
A quick refresher, because the whole problem comes from this.
You never store a password itself. You store a hash: the output of a one-way function, so the password can be checked but not read back. If someone steals the database, they get hashes, not passwords. They can still guess, though. They pick a likely password, hash it the same way, and see if it matches. Repeat a few billion times.
So a good password hash is deliberately slow. If checking one guess costs a fraction of a second, a real person signing in never notices, but an attacker trying billions of guesses has a much harder time. The slowness is the whole point. Every password-hashing method has a "work factor" setting that controls how slow it is. You turn it up as computers get faster.
That's where Workers come in. A setting that's barely noticeable on a normal server can be several times over the free plan's whole budget for a request.
The Options, Ruled Out One by One
The well-known password hashes are bcrypt, scrypt, and Argon2. bcrypt and scrypt typically take 70 ms or more at sensible settings, which is seven times the budget. They also use memory on purpose, to make attacks on graphics cards expensive. That's a strength on a server, but a poor fit for a runtime this tight. Better Auth, the sign-in library CKE uses, defaults to scrypt. So the default was out before I wrote a line of code.
That left PBKDF2. It's older and simpler. It runs a standard hash (here SHA-256) over and over, thousands of times, and the number of rounds is the work factor. It has one big advantage on Workers: it's built into the Web Crypto API that Workers already provide. There's no library to bundle, and the hashing runs as native code rather than JavaScript.
There's a catch. The Workers runtime refuses PBKDF2 above 100,000 iterations, on any plan. The usual recommendation for PBKDF2 with SHA-256, from the OWASP password storage guidance, is 600,000. That number simply can't run on Workers. Whatever I chose was going to be below the advice, and the real question was how far below.
Measuring It Myself
I found benchmarks from other open-source projects: about 13 ms at 100,000 iterations and about 6 ms at 50,000. Useful, but they were other people's accounts and other people's code. Workers' CPU time can vary by account, by region, and by what else the request is doing, and I was going to set a security setting based on this number. I wanted my own.
So I deployed a throwaway Worker to the project's own free account. It hashed a password with PBKDF2-SHA-256 at a given iteration count. I called it 8 times at each count and read the actual CPU time for each request from Cloudflare's live logs (wrangler tail), which report CPU time per request rather than wall-clock time. Then I deleted the Worker.
| Iterations | Median CPU time | Worst of 8 |
|---|---|---|
| 20,000 | 4 ms | 7 ms |
| 30,000 | 5 ms | 14 ms |
| 40,000 | 7.5 ms | 15 ms |
| 50,000 | 9.5 ms | 14 ms |
| 100,000 | 34 ms | not recorded |
A few things stood out.
The cost is roughly linear, until it isn't. 20,000 to 50,000 grew about as you'd expect. 100,000 jumped to 34 ms, well beyond double the 50,000 figure. I don't know exactly why, and I didn't need to. It was far over the limit either way.
The worst case is much worse than the median. Even at 30,000, one request in eight took 14 ms. Medians tell you what usually happens. The worst case tells you what a user will occasionally see.
Nothing failed. Not a single request was rejected, even the ones over 10 ms. The free plan clearly tolerates short bursts over the limit. I didn't want to build on that, because it isn't a promise anywhere, and a sign-in that works until Cloudflare tightens a rule is worse than one that was sized properly.
Choosing 30,000, Not 50,000
My plan going in was about 50,000 iterations, the highest count that looked like it would fit. The measurements changed my mind.
At 50,000 the hash alone took 9.5 ms. But a sign-in request does more than hash. It parses the request, looks up the user, checks the rate limit, creates a session, and writes it to the database. Waiting on the database doesn't count against CPU time, but all the code around it does. At 50,000, the hash would leave about half a millisecond for everything else.
At 30,000 the hash took about 5 ms. That leaves roughly half the budget for the rest of sign-in, with room for the bad days. I took that, and wrote the decision and its reason into the project's architecture document so it wouldn't look like an accident later.
The Code
Here's the hashing function, more or less exactly as it ships:
export const PBKDF2_ITERATIONS = 30_000;
const PREFIX = "pbkdf2-sha256";
async function derive(password: string, salt: Uint8Array, iterations: number) {
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(password),
"PBKDF2",
false,
["deriveBits"],
);
const bits = await crypto.subtle.deriveBits(
{ name: "PBKDF2", hash: "SHA-256", salt, iterations },
key,
256,
);
return new Uint8Array(bits);
}
export async function hashPassword(password: string): Promise<string> {
const salt = crypto.getRandomValues(new Uint8Array(16));
const hash = await derive(password, salt, PBKDF2_ITERATIONS);
return `${PREFIX}$${PBKDF2_ITERATIONS}$${b64(salt)}$${b64(hash)}`;
}
Two details matter more than the rest.
Every password gets its own random salt. The 16 random bytes are mixed into the hash, so two staff members with the same password get completely different hashes. An attacker can't reuse work across accounts, or look hashes up in a precomputed table.
The stored string records how it was made. A stored hash looks like pbkdf2-sha256$30000$<salt>$<hash>. The method and the iteration count travel with every hash. If I ever raise the count, say on a paid plan with more CPU, old passwords still check correctly, because each one says how many rounds it was made with. New passwords get the new count. It's a small thing that saves a painful migration later.
Checking a password reads those parts back, refuses anything malformed or over the runtime's 100,000 limit, re-derives the hash, and compares it:
const [prefix, iter, salt, expected] = hash.split("$");
const iterations = Number(iter);
if (prefix !== PREFIX || !salt || !expected || !(iterations > 0 && iterations <= 100_000))
return false;
const actual = await derive(password, unb64(salt), iterations);
const want = unb64(expected);
if (actual.length !== want.length) return false;
// Compare every byte, so the time taken doesn't reveal how much matched.
let diff = 0;
for (let i = 0; i < want.length; i++) diff |= actual[i]! ^ want[i]!;
return diff === 0;
That last loop is easy to skip past, so here's why it's there. A normal comparison stops at the first byte that differs. That means a guess that matches more of the hash takes slightly longer to reject, and with enough careful timing, those tiny differences can leak information. This loop always looks at every byte, so a nearly right guess and a wildly wrong one take the same time.
Plugging it into Better Auth is two lines, because the library lets you swap the hash function:
emailAndPassword: {
enabled: true,
disableSignUp: true,
minPasswordLength: 8,
password: { hash: hashPassword, verify: verifyPassword },
},
disableSignUp is there because nobody creates their own staff account. A manager does.
Making Up the Difference
30,000 iterations is about a twentieth of the recommended 600,000. Each guess costs an attacker roughly 20 times less work than the advice intends. I didn't want to pretend that away, so the rest of the sign-in design is built to narrow the gap.
Rate limiting. Sign-in allows 5 attempts a minute per IP address. On Workers, a simple counter is surprisingly hard to get right, because the code can run in many places at once, and two simultaneous attempts could both read "4" and both be let through. CKE stores each counter in a Durable Object, which handles one request at a time, so checking the count and adding to it happen in one step:
consume(window: number, max: number): { allowed: boolean; retryAfter: number | null } {
const now = Date.now();
if (now - this.windowStart >= window * 1000) {
this.windowStart = now;
this.count = 0;
}
if (this.count >= max) {
return {
allowed: false,
retryAfter: Math.ceil((this.windowStart + window * 1000 - now) / 1000),
};
}
this.count += 1;
return { allowed: true, retryAfter: null };
}
Better Auth hands each attempt to this object through its custom rate-limit storage setting. The counts live in memory, so if Cloudflare ever moves the object, the window simply starts again. That's acceptable for a sign-in limit.
Strong starting passwords. When a manager creates a staff account, the API makes a temporary password: 10 characters drawn from a 31-character set (lowercase letters and digits, with the look-alikes i, l, 1, o, and 0 removed), shown once as two groups like k7mpq-3xhtn. That's about 49 bits of randomness, far more than most people choose on their own. Staff must change it at their first sign-in, and until they do, the API refuses everything else.
Small blast radius. Customers and managers, the accounts with the most access and the most personal data, never have a password at all. They use Google. Passwords exist only for staff roles, and every one of them sees only simulated data.
Being Honest About the Limits
There's one thing rate limiting can't fix, and it matters to understand it. Rate limiting slows down someone guessing through the sign-in screen. It does nothing for someone who has already stolen the database. Offline, an attacker hashes guesses on their own hardware as fast as they like, and there the iteration count is the only defence. At 30,000, a weak staff password would fall faster than it would at 600,000. The strong temporary passwords help, but only until someone changes theirs to password1 (the minimum is 8 characters, with no other checks).
I accepted that for CKE because the accounts guard only demo data, and I wrote it down in the architecture document as a stated trade-off, not a hidden one. If this were a real kitchen handling real money, I'd change one of three things:
- Move staff to Google sign-in too. No passwords means nothing to hash, and the whole problem disappears. This was always the documented alternative.
- Use the paid Workers plan. At $5 a month, it allows far more CPU per request, enough to raise the iteration count a long way. Because each stored hash records its count, I could raise it without breaking existing passwords and re-hash each one at its next sign-in.
- Hash somewhere else. Hand the hashing to a service with no tight CPU limit. That adds a second system to run and secure, so it's my least favourite option.
What I Took Away
A platform limit can quietly pick a security setting for you. I didn't choose PBKDF2 because it's the best password hash. I chose it because it was the only one that fit. Knowing that, rather than finding out in production, meant I could design around it on purpose.
Measure on the platform you'll ship on. Other projects' benchmarks were close but not the same, and the worst-case figures only showed up in my own runs. Setting a security parameter from someone else's numbers would have been a guess.
Leave room under a hard limit. The highest setting that fits isn't the right one. The thing you measured is never the only work in the request.
Store hashes in a format that can grow. Putting the method and count into every hash costs nothing, and it turns a future upgrade from a migration into a config change.
Write the trade-off down. "Weaker than recommended, and here's why that's acceptable here" is a sentence a reviewer can check. A weaker setting with no explanation just looks like a mistake.
The full project, with all three apps and their downloads, is on the Casual Kitchen Express case study.