background-jobs
Skill0 starsChanged 35 days agoMITView on GitHub
Designing, implementing, and operating background job queues: picks the right backend (BullMQ, Celery, Sidekiq, pg-boss), makes jobs idempotent and safe to retry, sets concurrency and back-off correctly, handles dead-letter queues, and monitors job throughput and lag. Use when you want to add a background job, process tasks asynchronously, send emails in the background, set up a job queue, use BullMQ or Celery or Sidekiq, schedule a recurring task, handle retries, or process a queue.
- Installs packages
6 other projects use a version of this.
Adopted by
Most recently taken up by
- reddygopalkrishna/developer-agent-skillstheir own version, first seen Nov 8, 2026
- nimadorostkar/Claude-Skills-collectiontheir own version, first seen Oct 13, 2026
- nahid-sparktales/agent-dispatchertheir own version, first seen Sep 21, 2026
- novatic-cu/nova-skillstheir own version, first seen Sep 20, 2026
- MANVENDRA-github/agentrytheir own version, first seen Jul 6, 2026
- YepAPI/skillstheir own version, first seen Apr 12, 2026
Used with
Projects with it also use incident-response and observability.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
AnthropicSkillincident-response
Run an incident response workflow — triage, communicate, and write postmortem. Trigger with "we have an incident", "production is down", an alert that needs severity assessment, a status update mid-incident, or when writing a blameless postmortem after resolution.
Also in 4 projects that use this
OpenAISkillobservability
Vercel Observability expert guidance — Drains (logs, traces, speed insights, web analytics), Web Analytics, Speed Insights, runtime logs, custom events, OpenTelemetry integration, and monitoring dashboards. Use when instrumenting, debugging, or optimizing application performance and user experience on Vercel.
Also in 4 projects that use this
Other versions6 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 6
- nahid-sparktales/agent-dispatcher★ 59same name
- nimadorostkar/Claude-Skills-collection★ 33same name
- reddygopalkrishna/developer-agent-skills★ 8same name
- YepAPI/skills★ 8same name
- novatic-cu/nova-skills★ 1same name
- MANVENDRA-github/agentry★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository68 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/CLAUDE.mdCLAUDE.md
- accessibilitySkill
- api-designSkill
- api-versioningSkill
- authSkill
- cachingSkill
- capacity-planningSkill
- changelogSkill
- chaos-engineeringSkill
- ci-cdSkill
- circuit-breakerSkill
- claude-best-practicesSkill
- code-commentsSkill
- code-hygieneSkill
- code-reviewSkill
- code-structureSkill
- commit-styleSkill
- concurrency-and-lockingSkill
- database-transactionsSkill
- data-consistencySkill
- debug-infra-startupSkill
- debug-sessionSkill
- demo-video-creatorSkill
- demo-video-script-creatorSkill
- dependency-injectionSkill
- dependency-updateSkill
- disk-cleanupSkill
- distributed-tracingSkill
- dockerSkill
- env-configSkill
- env-setupSkill
- error-handlingSkill
- event-driven-architectureSkill
- feature-flagsSkill
- file-storageSkill
- graceful-shutdownSkill
- idempotencySkill
- input-validationSkill
- jars-engineering-blogsmithSkill
- jars-workshop-builderSkill
- licensingSkill
- loggingSkill
- memory-and-allocationsSkill
- migrate-dbSkill
- monitoringSkill
- multi-tenancySkill
- notificationsSkill
- openapiSkill
- paginationSkill
- perf-profileSkill
- pr-descriptionSkill
- query-optimizationSkill
- rate-limitingSkill
- refactorSkill
- releaseSkill
- runbook-writerSkill
- searchSkill
- secrets-auditSkill
- simplifySkill
- The first 60 shown.
The file
Show its rules and text
We split this skill into the rules it gives an agent
15 rules. 0 are common, 12 are distinctive, and 3 are very specific to this project.
0
Common
Most of the 6 edited versions we read keep these.
12
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
Add reliable background job processing to a service.
- Distinctive: line 15
Must survive a server restart (payment webhooks, invoice generation)
- Distinctive: line 20
Do not put work in a background job when:
- Distinctive: line 36
Use pg-boss if you already have Postgres and want to avoid adding Redis.
- Distinctive: line 42
Keep job payloads small and serialisable.
- Very specific: line 100
Use INSERT ... ON CONFLICT DO NOTHING for database writes.
- Very specific: line 101
Check a status field before sending a notification: if email.sent_at: return.
- Distinctive: line 126
Concurrency: start with 5–10 workers per queue.
- Distinctive: line 130
Timeout: always set a per-job timeout.
- Distinctive: line 185
Only schedule a job once — check if the repeatable job already exists before adding it:
- Very specific: line 242
Always set attempts and backoff — unbounded retries fill the queue forever.
- Distinctive: line 243
Never store secrets or PII in the job payload — store a reference ID and fetch at runtime.
- Distinctive: line 244
Never enqueue a job inside a database transaction — the job may run before the transaction commits, leading to "record not found" errors.
- Distinctive: line 246
Keep job handlers short. If a handler exceeds ~100 lines, extract helper functions.
- Distinctive: line 249
Test job handlers directly (call the handler function, not the queue) so tests don't need a live Redis.
“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
background-jobs
Add reliable background job processing to a service.
1. Decide what belongs in a background job
Move work out of the request/response cycle when it:
- Takes more than ~200 ms (email sending, PDF generation, image resizing)
- Must survive a server restart (payment webhooks, invoice generation)
- Can be retried independently (third-party API calls)
- Needs to be rate-limited or throttled (bulk notifications)
- Runs on a schedule (nightly reports, data cleanup)
Do not put work in a background job when:
- The HTTP response depends on the result (use async/await instead)
- The job is tiny and synchronous work is fine
- Failure must block the user action (use a database transaction instead)
2. Pick a queue backend
| Stack | Library | Queue backend |
| Node.js | BullMQ | Redis |
| Node.js (Postgres) | pg-boss | PostgreSQL |
| Python | Celery | Redis or RabbitMQ |
| Ruby | Sidekiq | Redis |
| Go | asynq | Redis |
| Any | Temporal | Temporal server (durable workflows) |
Use pg-boss if you already have Postgres and want to avoid adding Redis. Use BullMQ or Sidekiq for high-throughput queues. Use Temporal when jobs are multi-step workflows that need to survive partial failure.
3. Define a job
Keep job payloads small and serialisable. Store large data in the database and pass an ID.
// Node.js + BullMQ
// types/jobs.ts — shared payload types
export interface SendEmailJobData {
to: string;
templateId: string;
vars: Record<string, string>;
idempotencyKey: string; // always include — used to deduplicate retries
}
// queues/email.ts
import { Queue } from 'bullmq';
import { redis } from '../lib/redis';
export const emailQueue = new Queue<SendEmailJobData>('email', {
connection: redis,
defaultJobOptions: {
attempts: 5,
backoff: { type: 'exponential', delay: 1000 }, // 1s, 2s, 4s, 8s, 16s
removeOnComplete: { count: 1000 },
removeOnFail: { count: 5000 },
},
});# Python + Celery
# tasks/email.py
from celery import shared_task
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
@shared_task(
bind=True,
max_retries=5,
default_retry_delay=60,
acks_late=True, # acknowledge only after the task succeeds
reject_on_worker_lost=True,
)
def send_email(self, to: str, template_id: str, vars: dict, idempotency_key: str):
try:
email_client.send(to=to, template=template_id, variables=vars)
except TemporaryError as exc:
raise self.retry(exc=exc, countdown=2 ** self.request.retries * 30)4. Make every job idempotent
A job will run more than once — Redis crashes, workers restart, networks blip. Design each job so running it twice produces the same result as running it once.
Techniques:
- Include an
idempotencyKeyin the payload; check it before doing work. - Use
INSERT ... ON CONFLICT DO NOTHINGfor database writes. - Check a status field before sending a notification:
if email.sent_at: return. - For external API calls, use the provider's idempotency key header.
// workers/email.worker.ts
import { Worker } from 'bullmq';
import type { SendEmailJobData } from '../types/jobs';
new Worker<SendEmailJobData>('email', async (job) => {
const already = await db.emailLog.findUnique({ where: { key: job.data.idempotencyKey } });
if (already) {
job.log(`Skipping duplicate — already sent at ${already.sentAt}`);
return;
}
await emailProvider.send(job.data);
await db.emailLog.create({
data: { key: job.data.idempotencyKey, sentAt: new Date() },
});
}, { connection: redis, concurrency: 5 });5. Set concurrency and back-off correctly
- Concurrency: start with 5–10 workers per queue. Tune based on CPU, memory, and the external service's rate limit.
- Exponential back-off: double the delay on each retry to avoid hammering a struggling dependency. Add jitter (±10%) to spread load across workers.
- Timeout: always set a per-job timeout. A hanging job blocks a worker slot forever.
new Worker('email', handler, {
connection: redis,
concurrency: 10,
lockDuration: 30_000, // job must complete within 30 s or another worker can claim it
});6. Handle failure and dead-letter queues
Jobs that exhaust their retries land in the failed set. Process them:
- Alert on a spike in failed jobs (see step 8).
- Investigate the failure reason in the job's
failedReasonfield. - Fix the bug, then either replay the jobs or discard them after logging.
// Replay all failed jobs in a queue (BullMQ)
import { Queue } from 'bullmq';
const q = new Queue('email', { connection: redis });
const failed = await q.getFailed();
for (const job of failed) {
await job.retry();
}For Celery, use a dedicated dead-letter queue in RabbitMQ or inspect the failed task store:
celery -A myapp inspect reserved
celery -A myapp result <task-id>7. Schedule recurring jobs
// BullMQ — cron-style repeatable job
await emailQueue.add(
'weekly-digest',
{ templateId: 'weekly-digest', to: 'all-users' },
{ repeat: { pattern: '0 9 * * 1' } } // every Monday at 09:00
);# Celery beat schedule
CELERY_BEAT_SCHEDULE = {
'weekly-digest': {
'task': 'tasks.email.send_weekly_digest',
'schedule': crontab(hour=9, minute=0, day_of_week='monday'),
},
}Only schedule a job once — check if the repeatable job already exists before adding it:
const repeatable = await emailQueue.getRepeatableJobs();
const exists = repeatable.some((r) => r.name === 'weekly-digest');
if (!exists) await emailQueue.add('weekly-digest', payload, { repeat: { pattern: '...' } });8. Monitor queue health
Track these signals:
| Metric | Alert threshold |
| Queue depth (waiting) | Sustained > 1000 for 5 min |
| Job failure rate | > 1 % of completions over 10 min |
| Processing latency (wait time) | p99 > 30 s |
| Worker count | < 1 active worker |
BullMQ + Bull Board (local dashboard):
npm install @bull-board/expressimport { createBullBoard } from '@bull-board/api';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';
import { ExpressAdapter } from '@bull-board/express';
const serverAdapter = new ExpressAdapter().setBasePath('/admin/queues');
createBullBoard({ queues: [new BullMQAdapter(emailQueue)], serverAdapter });
app.use('/admin/queues', serverAdapter.getRouter());Expose queue metrics to Prometheus via bullmq-prometheus or a custom collector, then
alert in Grafana.
9. Graceful shutdown
Workers must drain in-flight jobs before the process exits, or jobs will be requeued
(BullMQ) or lost (if acks_late=False in Celery).
// BullMQ graceful shutdown
const worker = new Worker('email', handler, { connection: redis });
process.on('SIGTERM', async () => {
await worker.close(); // waits for current jobs to finish, stops accepting new ones
process.exit(0);
});# Celery handles SIGTERM gracefully by default when acks_late=True
# Send SIGTERM to the worker process; it finishes current tasks before stopping.Rules
- Always set
attemptsandbackoff— unbounded retries fill the queue forever. - Never store secrets or PII in the job payload — store a reference ID and fetch at runtime.
- Never enqueue a job inside a database transaction — the job may run before the transaction commits, leading to "record not found" errors.
- Keep job handlers short. If a handler exceeds ~100 lines, extract helper functions.
- One queue per concern (email, notifications, reports) — mixing unrelated jobs in one queue makes it impossible to tune concurrency or prioritise independently.
- Test job handlers directly (call the handler function, not the queue) so tests don't need a live Redis.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

