cd /news/ai-tools/one-redis-five-jobs-how-upstash-keep… · home › topics › ai-tools › article
[ARTICLE · art-179522] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=↑ positive

One Redis, five jobs: how Upstash keeps my job board's AI costs and serverless state in check

A developer behind PMHNP Hiring, a niche job board for psychiatric nurse practitioners, detailed how a single Upstash Redis database handles five jobs across the site's Vercel-hosted Next.js app, including rate limiting, AI response caching and serverless shared state. The AI gateway checks the cache before spending rate-limit budget, so repeat requests return instantly without consuming a slot or triggering a paid model call. The developer also described keying rate limits by route and IP, with shared budgets for crawlers that rotate addresses.

recommendation

Put a cache lookup ahead of your rate limiter in the AI gateway so cached responses skip both the slot and the provider call, and key known crawlers by name rather than IP.

more in playbook: Controlling LLM cost
by read9 min views5 publishedDec 1, 2026

Sponsored by Upstash. I picked the topic, the code is from my production app, and the opinions are mine. I was running Upstash Redis on this site before they reached out.

Upstash found me through my earlier post on rate limiting Next.js routes for scrapers. This is the sequel: everything else Redis ended up doing.

PMHNP Hiring runs on Vercel, so no two requests are guaranteed to share memory. One Upstash Redis database is the shared memory the app doesn't otherwise have. It does five jobs:

Below is the real code for each, what broke along the way, and what I'd change.

PMHNP Hiring is a niche job board for psychiatric nurse practitioners. It's Next.js on Vercel, Postgres on Supabase through Prisma, and a handful of AI features: resume review, cover letters, candidate scoring for employers, and a re-ranker for talent search.

I wrote earlier about rate limiting Next.js API routes for scrapers. That covered IP limits. This post is everything else Redis ended up doing once it was in the stack.

Every module creates its client the same way, and every one of them works without Redis:

import { Redis } from '@upstash/redis';

const redis = process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN
    ? new Redis({
        url: process.env.UPSTASH_REDIS_REST_URL,
        token: process.env.UPSTASH_REDIS_REST_TOKEN,
    })
    : null;

Why Upstash and not a Redis box: it speaks HTTP, so it works from serverless and edge functions with no connection pool to babysit, and it bills per request, which fits a site whose traffic comes in waves. Versions in this post: @upstash/redis 1.41 and @upstash/ratelimit 2.2.

Every limit in the app lives in one table. There are 24 of them, from "3 job posts a minute" to "10 candidate messages a day":

export const RATE_LIMITS = {
    postJob: { limit: 3, windowSeconds: 60 },
    auth: { limit: 10, windowSeconds: 60 },
    publicDetail: { limit: 240, windowSeconds: 60 },
    candidateMessage: { limit: 10, windowSeconds: 86400 },
    dataRequest: { limit: 3, windowSeconds: 3600 },
    // ...19 more
} as const;

The check itself is a thin wrapper around @upstash/ratelimit with a sliding window:

const limiter = new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(config.limit, `${config.windowSeconds} s`),
    analytics: true,
    prefix: '@upstash/ratelimit',
});
const { success, reset, remaining } = await limiter.limit(key);

The interesting part turned out to be the key, not the algorithm. Three shapes cover everything:

ratelimit:<route>:<ip> for anonymous traffic.ratelimit:shared:crawler:<name> for known crawlers, shared across all of their IPs. A crawler that rotates IPs still gets one budget: 10 requests a minute, the same pace its robots.txt Crawl-delay asks for. Over the limit, the route gets a proper 429 with Retry-After and X-RateLimit-Reset headers, so well-behaved clients back off on their own.

Every AI call in the app goes through one gateway function. The order of operations inside it is the whole trick:

// 1. Cache lookup: free, and it does NOT spend rate-limit budget
const cached = await readCache<T>(req.task, cacheKeyParts);
if (cached.hit) return cached.response;

// 2. Rate limit: only live provider calls pay
const rl = await checkAiRateLimit(req.task, req.tenant, task.rateLimit);
if (!rl.success) throw new AiGatewayError('...', 'rate_limited');

// 3. Call the model, validate, then write the cache
await writeCache(req.task, cacheKeyParts, response, task.cacheTtlSeconds);

Cache first means a user who double-clicks "Review my resume" gets the same answer instantly, isn't charged a slot, and I'm not charged a call.

The cache key is a SHA-256 of whatever identifies the input, plus a hash of the prompt file itself:

function buildCacheKey(task: AiTaskId, parts: readonly unknown[]): string {
    const hash = createHash('sha256')
        .update(parts.map((p) => JSON.stringify(p ?? null)).join('|'))
        .digest('hex');
    return `ai:cache:v1:${task}:${hash}`;
}

That prompt hash was a lesson. Early on, I'd edit a prompt, ship it, and keep getting yesterday's answers out of the cache. Now editing the prompt file changes the key, so stale answers simply stop matching. The v1 segment is the manual escape hatch for when the output shape changes.

TTL is set per task, because "cacheable" depends on what the user expects:

Task TTL Why
Candidate scoring 24 hours Same job and same candidate give the same score
Resume parsing 7 days A file's text doesn't change
Talent search re-rank 10 minutes Searches repeat fast within one session
Resume review 1 hour Absorbs double clicks; an edit changes the key anyway
Cover letter, resume tailoring none Each generation should feel fresh

Cache reads and writes fail quietly. If Redis is down, the user still gets an answer, just without the savings.

I won't quote a savings percentage I haven't measured cleanly. What I can say is how it's tracked: every cache hit is logged next to the live calls with a cost of $0, so the cost dashboard shows the real split per task instead of an estimate, and a hit never inflates the bill it's supposed to shrink.

The AI limiter uses the same library with its own prefix, so AI budgets never share a window with HTTP budgets:

const key = `ai:rl:${task}:${tenant.type}:${tenant.id}`;
const limiter = new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(limit.limit, `${limit.windowSeconds} s`),
    prefix: 'ai-gateway',
    analytics: false,
});

The tenant is an employer, a candidate or the system. Each of the 16 AI tasks has its own hourly ceiling, from 10 an hour for career-path analysis to 5,000 an hour for embeddings. This is the guardrail that answers the classic question of how you stop one user from running up your OpenAI bill.

The free resume tools allow three reviews a day. My first version counted that day's rows in the AI call log before each call. It had two bugs:

Redis fixes both with a reserve-then-release pattern:

const key = `resume-studio:aiquota:${task}:${userId}:${dayBucket()}`;

const count = await redis.incr(key);
if (count === 1) await redis.expire(key, secondsUntilReset());
if (count > cap) {
    await redis.decr(key); // undo our over-cap increment
    return { allowed: false };
}
return { allowed: true };

INCR is atomic, so the fourth request in a burst sees 4 and is turned away, however many arrive together. If the model call then fails, the route calls releaseDailyQuota(), which runs DECR, so only successful generations count. The day bucket in the key means yesterday's counters can never match again, and the TTL cleans them up at midnight Central.

One deliberate choice: if Redis itself errors, this quota fails open. A missed limit on three free resume reviews costs me a few cents. Blocking a job seeker because my cache hiccuped costs more.

Two problems here had nothing to do with rate limiting, and Redis was still the right tool.

A shared Google quota. Google's Indexing API gives the project about 200 publish requests a day, and five different jobs send them: every ingest run, a couple of crons, and the instant ping when an employer pays for a post. Each one capped itself per run, but none knew what the others had sent. The same URL went out two to five times, and by the afternoon the quota was gone, so the paying customer's ping was the one Google never got.

The fix is a claim per URL with SET NX EX:

async function claim(url: string, type: NoticeType): Promise<boolean> {
    const key = claimKey(url, type);           // sha1 of the URL
    const ttl = RESEND_WINDOW_SECONDS[type];  // 26h for updates, 72h for deletes
    return (await redis.set(key, 1, { nx: true, ex: ttl })) === 'OK';
}

Whoever sets the key first sends the notice. Everyone else gets null and skips it. Day counters next to the claims track how much of the 200 is left, so paid posts can be given priority.

Chunked cron jobs. Some job sources are too big to pull in one serverless run, so the cron splits them into chunks. To detect jobs that disappeared from a source, though, I need the union of every chunk. Each chunk writes its IDs to Redis under a run bucket, and the last one to finish aggregates:

await redis.set(chunkKey, JSON.stringify(payload), { ex: KEY_TTL_SECONDS }); // 12h
// ...when every chunk for this run bucket exists, read them all, check, then delete

This one taught me something about silent failures. I cut a source from 8 chunks to 4 but left the aggregator expecting 8. It never saw a complete run, so it never aggregated. Nothing errored; the keys just expired every cycle. The TTL that keeps Redis tidy also hid the bug. Now the chunk count lives in one constant that the cron schedule has to match.

Every module above has an in-memory fallback, and I want to be honest about what that is: on serverless it's barely a limit. Each instance counts on its own, so a burst spread over ten instances gets ten times the budget.

So the fallback is for local development, and in production a Redis failure is treated as an incident:

/api/health pings Redis with a 2-second deadline and reports up, down or unconfigured, so monitoring can tell when every limit has gone soft.

await Promise.race([redis.ping(), deadline]); // deadline rejects after 2,000 ms
return { status: 'up', latencyMs: Date.now() - started };

Very little. My Upstash invoice for October was $5.87: $5.86 of requests and one cent of storage. For November, Upstash's own billing email on the 25th projected this database at about $10 on pay-as-you-go. That one database carries all five jobs above, for a site that also gets a steady crawl from search engines and AI bots.

Honest notes from reading my own code back for this post:

new Ratelimit(...) on every call. It works, but it throws away the library's in-memory ephemeral cache, which can turn away a blocked client without a Redis round trip. A small map of limiters per config would keep it.analytics: true. lib/redis.ts. reset is the start of the next window, not an exact time. That's fine for abuse protection; don't build billing on it. I added Redis to stop scrapers. It ended up as the shared memory a serverless app is missing: limits, caches, quotas, claims and handoffs between jobs, from one HTTP-based database that costs about as much as a lunch.

If you're on Vercel or any serverless platform and keep reaching for "just store it in memory", that's usually the sign. Upstash's Redis docs are a good place to start, and the ratelimit SDK gets you to a working limit in a few lines.

Questions or a pattern I missed? I'm on dvskr.dev.

── more in #ai-tools 4 stories · sorted by recency
── more on @upstash 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/one-redis-five-jobs-…] indexed:0 read:9min 2026-12-01 · —