Background Jobs & Queues
Relevant source files
The following files were used as context for generating this wiki page:The Inbox Zero application relies on a system of background jobs and queues to perform long-running, asynchronous tasks without blocking the user interface. This is crucial for operations like the "Clean Inbox" feature, which processes a large number of emails. The primary technologies used for this are Upstash QStash for message queuing and Redis for state management, along with Next.js Server Actions and API routes that act as job producers and consumers.
This architecture allows the application to defer heavy processing, manage API rate limits, and provide a responsive user experience. Jobs are enqueued from server actions and processed by dedicated API endpoints that act as webhooks for the queueing service.
Sources: ARCHITECTURE.md, apps/web/utils/actions/clean.ts
Core Technologies
The background job system is built upon a few key services and patterns.
| Technology / Pattern | Purpose | Source Files - |
| Upstash QStash | A serverless message queue service used to enqueue and consume background jobs via HTTP requests (webhooks). | apps/web/utils/actions/clean.ts:119, apps/web/app/api/clean/route.ts:1 - |
| Upstash Redis | Used for caching and storing the state of ongoing jobs, such as which email threads are being processed or have been completed. | README.md:104, apps/web/app/api/clean/route.ts:18, apps/web/utils/redis/clean.ts - |
| next/server after() | A Next.js-specific function that allows a process to run after a response has been sent to the client. This is used to kick off the job enqueueing process without making the user wait. | apps/web/utils/actions/clean.ts:133 - |
| p-queue | A client-side library used to manage concurrency for API requests from the browser, ensuring that not too many requests are sent simultaneously. | apps/web/app/(app)/[emailAccountId]/assistant/ProcessRules.tsx:201 - |
| Cron Jobs | Scheduled tasks used for periodic maintenance and triggering recurring workflows, such as checking for new emails. | README.md:231-243 - |
Email Cleaning Workflow
The "Clean Inbox" feature is a prime example of the background job architecture. It involves a multi-step, chained queuing process to analyze and act on a large volume of emails efficiently.
This diagram illustrates the sequence of events when a user initiates an inbox cleaning job.
1. Job Initiation (cleanInboxAction)
The process begins when the user triggers the cleanInboxAction server action.
- Immediate Response: The action immediately returns a
jobIdto the user. - Deferred Processing: The core logic is wrapped in a
after(() => process())call. This ensures the heavy lifting begins only after the HTTP response has been sent, preventing a timeout on the client-side. - Job Creation: Inside the
afterblock, acleanupJobrecord is created in the Prisma database to track the overall task. - Enqueueing: The function fetches email threads from Gmail and then uses
bulkPublishToQstashto create individual jobs for each thread. These jobs are sent to the/api/cleanwebhook endpoint.
A key aspect is the flowControl configuration, which sets a parallelism limit for jobs associated with a specific user (ai-clean-${emailAccountId}), helping to manage rate limits and resource consumption.
Sources: apps/web/utils/actions/clean.ts:22-135
2. Initial Processing (/api/clean)
This API route acts as the first consumer in the chain. It is a QStash webhook that receives a CleanThreadBody payload for a single email thread.
Its responsibilities are:
- Fetch the full messages for the given
threadId. - Save the initial state of the thread to Redis using
saveThread. - Apply a series of static rules and checks (e.g., skip starred emails, skip conversations, check for calendar events).
- If no static rule matches, it may perform an AI-based check using
aiClean. - Based on the outcome, it enqueues a second job to the
/api/clean/gmailendpoint. This new job contains the final decision (e.g.,markDone: true). - It updates the thread's status in Redis to
applying.
This two-step process separates the decision-making logic (in /api/clean) from the action-execution logic (in /api/clean/gmail).
Sources: apps/web/app/api/clean/route.ts:39-165
3. Final Action (/api/clean/gmail)
This is the final webhook in the cleaning workflow. It receives a CleanGmailBody payload with a simple directive.
- It authenticates a Gmail client.
- It performs the requested action on the thread, such as adding/removing labels (
labelThread) to archive or mark as read. - It saves the final result to the
CleanupThreadtable in the database. - It updates the thread's status in Redis to
completed.
This endpoint is designed to be lightweight, solely responsible for executing a pre-determined action against the Gmail API. Rate limiting for this endpoint is also managed via QStash.
Sources: apps/web/app/api/clean/gmail/route.ts:28-80
Client-Side Queuing
In addition to backend job queues, the application also employs client-side queuing to manage concurrent API requests from the browser. The ProcessRulesContent component uses the p-queue library to process multiple emails without overwhelming the browser or the backend.
This diagram shows the client-side flow for running rules on all emails.
- When a user clicks "Run on All", a
PQueueinstance is created with a concurrency limit (e.g., 3). - The component iterates through pages of emails.
- For each email that hasn't been processed, it adds an
onRuntask to the queue. p-queueensures that no more than 3onRuntasks (which make API calls) are running at any given time.
Sources: apps/web/app/(app)/[emailAccountId]/assistant/ProcessRules.tsx:199-247
Scheduled Jobs (Cron)
The application also defines cron jobs for periodic tasks. These are configured to hit specific API endpoints on a schedule.
| Path | Schedule | Purpose |
|---|---|---|
/api/watch/all | 0 1 * * * | Renews the Google Pub/Sub watch on all user inboxes daily. |
/api/resend/summary/all | 0 16 * * 1 | Sends a weekly summary email to users. |
/api/reply-tracker/disable-unused-auto-draft | 0 3 * * * | Disables auto-drafting for unused reply tracking rules. |
These jobs are essential for maintaining the application's real-time capabilities and performing routine maintenance.
Sources: README.md:232-242