{"slug": "one-redis-five-jobs-how-upstash-keeps-my-job-board-s-ai-costs-and-serverless-in", "title": "One Redis, five jobs: how Upstash keeps my job board's AI costs and serverless state in check", "summary": "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.", "body_md": "*Sponsored by [Upstash](https://upstash.com/?utm_source=sathish-daggula). 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.*\n\n*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.*\n\nPMHNP 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:\n\nBelow is the real code for each, what broke along the way, and what I'd change.\n\n[PMHNP Hiring](https://pmhnphiring.com) 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.\n\nI wrote earlier about [rate limiting Next.js API routes for scrapers](https://dev.to/sathish_daggula/how-to-rate-limit-nextjs-api-routes-for-scrapers-1p34). That covered IP limits. This post is everything else Redis ended up doing once it was in the stack.\n\nEvery module creates its client the same way, and every one of them works without Redis:\n\n``` js\nimport { Redis } from '@upstash/redis';\n\nconst redis = process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN\n    ? new Redis({\n        url: process.env.UPSTASH_REDIS_REST_URL,\n        token: process.env.UPSTASH_REDIS_REST_TOKEN,\n    })\n    : null;\n```\n\nWhy 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.\n\nEvery 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\":\n\n``` js\nexport const RATE_LIMITS = {\n    postJob: { limit: 3, windowSeconds: 60 },\n    auth: { limit: 10, windowSeconds: 60 },\n    publicDetail: { limit: 240, windowSeconds: 60 },\n    candidateMessage: { limit: 10, windowSeconds: 86400 },\n    dataRequest: { limit: 3, windowSeconds: 3600 },\n    // ...19 more\n} as const;\n```\n\nThe check itself is a thin wrapper around [`@upstash/ratelimit`](https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted?utm_source=sathish-daggula) with a sliding window:\n\n``` js\nconst limiter = new Ratelimit({\n    redis,\n    limiter: Ratelimit.slidingWindow(config.limit, `${config.windowSeconds} s`),\n    analytics: true,\n    prefix: '@upstash/ratelimit',\n});\nconst { success, reset, remaining } = await limiter.limit(key);\n```\n\nThe interesting part turned out to be the key, not the algorithm. Three shapes cover everything:\n\n`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.\nOver 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.\n\nEvery AI call in the app goes through one gateway function. The order of operations inside it is the whole trick:\n\n``` js\n// 1. Cache lookup: free, and it does NOT spend rate-limit budget\nconst cached = await readCache<T>(req.task, cacheKeyParts);\nif (cached.hit) return cached.response;\n\n// 2. Rate limit: only live provider calls pay\nconst rl = await checkAiRateLimit(req.task, req.tenant, task.rateLimit);\nif (!rl.success) throw new AiGatewayError('...', 'rate_limited');\n\n// 3. Call the model, validate, then write the cache\nawait writeCache(req.task, cacheKeyParts, response, task.cacheTtlSeconds);\n```\n\nCache 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.\n\nThe cache key is a SHA-256 of whatever identifies the input, plus a hash of the prompt file itself:\n\n```\nfunction buildCacheKey(task: AiTaskId, parts: readonly unknown[]): string {\n    const hash = createHash('sha256')\n        .update(parts.map((p) => JSON.stringify(p ?? null)).join('|'))\n        .digest('hex');\n    return `ai:cache:v1:${task}:${hash}`;\n}\n```\n\nThat 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.\n\nTTL is set per task, because \"cacheable\" depends on what the user expects:\n\n| Task | TTL | Why | \n|---|---|---|\n| Candidate scoring | 24 hours | Same job and same candidate give the same score | \n| Resume parsing | 7 days | A file's text doesn't change | \n| Talent search re-rank | 10 minutes | Searches repeat fast within one session | \n| Resume review | 1 hour | Absorbs double clicks; an edit changes the key anyway | \n| Cover letter, resume tailoring | none | Each generation should feel fresh | \n\nCache reads and writes fail quietly. If Redis is down, the user still gets an answer, just without the savings.\n\nI 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.\n\nThe AI limiter uses the same library with its own prefix, so AI budgets never share a window with HTTP budgets:\n\n``` js\nconst key = `ai:rl:${task}:${tenant.type}:${tenant.id}`;\nconst limiter = new Ratelimit({\n    redis,\n    limiter: Ratelimit.slidingWindow(limit.limit, `${limit.windowSeconds} s`),\n    prefix: 'ai-gateway',\n    analytics: false,\n});\n```\n\nThe 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.\n\nThe 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:\n\nRedis fixes both with a reserve-then-release pattern:\n\n``` js\nconst key = `resume-studio:aiquota:${task}:${userId}:${dayBucket()}`;\n\nconst count = await redis.incr(key);\nif (count === 1) await redis.expire(key, secondsUntilReset());\nif (count > cap) {\n    await redis.decr(key); // undo our over-cap increment\n    return { allowed: false };\n}\nreturn { allowed: true };\n```\n\n`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.\n\nOne 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.\n\nTwo problems here had nothing to do with rate limiting, and Redis was still the right tool.\n\n**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.\n\nThe fix is a claim per URL with `SET NX EX`:\n\n```\nasync function claim(url: string, type: NoticeType): Promise<boolean> {\n    const key = claimKey(url, type);           // sha1 of the URL\n    const ttl = RESEND_WINDOW_SECONDS[type];  // 26h for updates, 72h for deletes\n    return (await redis.set(key, 1, { nx: true, ex: ttl })) === 'OK';\n}\n```\n\nWhoever 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.\n\n**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:\n\n```\nawait redis.set(chunkKey, JSON.stringify(payload), { ex: KEY_TTL_SECONDS }); // 12h\n// ...when every chunk for this run bucket exists, read them all, check, then delete\n```\n\nThis 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.\n\nEvery 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.\n\nSo the fallback is for local development, and in production a Redis failure is treated as an incident:\n\n`/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.\n\n```\nawait Promise.race([redis.ping(), deadline]); // deadline rejects after 2,000 ms\nreturn { status: 'up', latencyMs: Date.now() - started };\n```\n\nVery 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.\n\nHonest notes from reading my own code back for this post:\n\n`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.\nI 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.\n\nIf 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](https://upstash.com/docs/redis?utm_source=sathish-daggula) are a good place to start, and the [ratelimit SDK](https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted?utm_source=sathish-daggula) gets you to a working limit in a few lines.\n\nQuestions or a pattern I missed? I'm on [dvskr.dev](https://dvskr.dev).", "url": "https://wpnews.pro/news/one-redis-five-jobs-how-upstash-keeps-my-job-board-s-ai-costs-and-serverless-in", "canonical_source": "https://dev.to/sathish_daggula/one-redis-five-jobs-how-upstash-keeps-my-job-boards-ai-costs-and-serverless-state-in-check-2bj0", "published_at": "2026-12-01 16:08:40+00:00", "updated_at": "2026-12-01 16:14:03.663811+00:00", "lang": "en", "topics": ["ai-tools", "ai-infrastructure", "mlops", "developer-tools", "ai-agents"], "entities": ["Upstash", "PMHNP Hiring", "Vercel", "Next.js", "Supabase", "Prisma"], "also_reported_by": [], "takeaway": "Checking the AI response cache before the rate limiter means repeat requests cost neither a rate-limit slot nor a provider call, and keying crawler limits as ratelimit:shared:crawler:<name> gives IP-rotating bots one shared budget.", "recommendation": {"advice": "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.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/one-redis-five-jobs-how-upstash-keeps-my-job-board-s-ai-costs-and-serverless-in", "markdown": "https://wpnews.pro/news/one-redis-five-jobs-how-upstash-keeps-my-job-board-s-ai-costs-and-serverless-in.md", "text": "https://wpnews.pro/news/one-redis-five-jobs-how-upstash-keeps-my-job-board-s-ai-costs-and-serverless-in.txt", "jsonld": "https://wpnews.pro/news/one-redis-five-jobs-how-upstash-keeps-my-job-board-s-ai-costs-and-serverless-in.jsonld"}}