AiCredits
Queue DeepSeek Jobs

Async Job Queues for LLM Workloads: Celery vs Serverless Functions

Compare Celery and serverless functions for async LLM job queues: retries, rate limits, timeouts, idempotency, and practical DeepSeek API examples.

Published 2026-11-27 Updated 2026-11-27 7 min

Async Job Queues for LLM Workloads: Celery vs Serverless Functions

LLM calls are not like resizing an image. They are long-tailed, rate-limited, and occasionally fail in ways that should be retried. The queue you put in front of the model matters as much as the model choice. This guide compares Celery and serverless functions for async LLM workloads, with runnable code that calls DeepSeek through the OpenAI SDK at AiCredits.

The short version: serverless functions are compute, not a queue. Celery is a queue plus worker runtime. If you compare only the compute, you will miss the part that controls concurrency, retries, and idempotency. Pick the queue and control plane first, then decide where the call runs.

The real decision: where does rate-limit coordination live?

LLM workloads have a shared bottleneck: the API key and model. A burst of retries can turn one rate-limit response into a self-inflicted outage. Celery gives you a natural place to coordinate: a fixed worker pool, worker_concurrency, and a shared token bucket in Redis. You can route cheap bulk jobs to deepseek-v4-flash and harder reasoning jobs to deepseek-v4-pro by queue.

Serverless gives you elastic compute, but each invocation is isolated. You need a managed queue in front (SQS, Cloud Tasks, etc.) and a concurrency cap at the queue or function level. If you simply let the platform scale, you will hit the model's limits faster. The fix is to cap concurrency per API key/model and make retries jittered and bounded.

# tasks.py
import os
from celery import Celery
from celery.utils.log import get_task_logger
from openai import (
    OpenAI,
    APIConnectionError,
    APITimeoutError,
    RateLimitError,
    InternalServerError,
)

app = Celery('llm_jobs', broker=os.environ['REDIS_URL'], backend=os.environ['REDIS_URL'])
app.conf.update(
    task_acks_late=True,
    worker_prefetch_multiplier=1,
    task_reject_on_worker_lost=True,
)

logger = get_task_logger(__name__)
client = OpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
)

RETRYABLE = (APIConnectionError, APITimeoutError, RateLimitError, InternalServerError)

@app.task(bind=True, max_retries=5, default_retry_delay=2)
def summarize_text(self, job_id: str, text: str) -> dict:
    try:
        response = client.chat.completions.create(
            model='deepseek-v4-flash',
            messages=[
                {'role': 'system', 'content': 'Summarize the user text in three bullet points.'},
                {'role': 'user', 'content': text},
            ],
            temperature=0.2,
        )
        summary = response.choices[0].message.content
        # Write result keyed by job_id in your database here.
        return {'job_id': job_id, 'summary': summary}
    except RETRYABLE as exc:
        countdown = min(60, 2 ** self.request.retries)
        logger.warning('Retryable LLM error for %s: %s', job_id, exc)
        raise self.retry(exc=exc, countdown=countdown)

This Celery task uses acks_late so a crashed worker does not silently lose a job, prefetch_multiplier=1 so one worker does not hoard a batch, and retries only on transient errors. The job_id is your idempotency handle: write results and status keyed by it.

Use deepseek-v4-flash as the default for summaries, extraction, classification, and other high-volume jobs. Switch to deepseek-v4-pro only when the task needs stronger reasoning; pro costs more, so route it deliberately.

Serverless functions: pair them with a real queue

A Lambda function on its own is not an async queue. For LLM jobs, use SQS or a managed task queue with a dead-letter queue, set the function timeout above your expected model tail latency, and cap reserved concurrency. Treat the function as a single attempt: if the model returns a retryable error, raise so the queue redelivers.

Do not retry inside the function and also retry at the queue level. Pick one layer. SQS is at-least-once, so the same job_id can arrive twice; store an idempotency record before writing the final result.

# lambda_function.py
import json
import os
from openai import (
    OpenAI,
    APIConnectionError,
    APITimeoutError,
    RateLimitError,
    InternalServerError,
)

client = OpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
)

RETRYABLE = (APIConnectionError, APITimeoutError, RateLimitError, InternalServerError)

def handler(event, context):
    # SQS event source: one record per invocation.
    record = event['Records'][0]
    data = json.loads(record['body'])
    job_id = data['job_id']
    text = data['text']

    try:
        response = client.chat.completions.create(
            model='deepseek-v4-flash',
            messages=[
                {'role': 'system', 'content': 'Summarize the user text in three bullet points.'},
                {'role': 'user', 'content': text},
            ],
            temperature=0.2,
        )
        # Store the result keyed by job_id before returning.
        return {'job_id': job_id, 'summary': response.choices[0].message.content}
    except RETRYABLE as exc:
        # Raise so SQS redelivers; after maxReceiveCount it goes to the DLQ.
        raise RuntimeError(f'Retryable LLM error for {job_id}: {type(exc).__name__}') from exc

The handler above is intentionally thin. The queue owns retries and the DLQ; the function owns the model call and result write. That separation is what makes serverless workable for LLM jobs.

Serverless is a good fit for spiky traffic, low-ops teams, and short-to-medium jobs. Celery is a better fit when you need long-running workers, custom routing, priority queues, or fine-grained concurrency control. Neither is universally cheaper: Celery shifts cost to always-on workers and ops time; serverless shifts cost to invocations and managed queue features. Use qualitative tradeoffs, not a single benchmark.

DimensionCeleryServerless + managed queue
Execution modelLong-lived workers consume from a brokerShort-lived functions triggered by a queue
Rate-limit controlWorker concurrency plus shared token bucketReserved concurrency plus queue concurrency cap
RetriesTask-level retries, acks_late, custom backoffQueue redrive and DLQ; raise to retry
Ops burdenYou run broker and workersProvider runs compute; you configure queue
Best fitSteady volume, custom routing, long jobsSpiky traffic, low ops, short-to-medium jobs
Watch outWorker hoarding, stuck tasksFunction timeouts, duplicate delivery, cold starts

What I recommend for LLM queues

  • Start with the queue you can operate. If you already run Redis or RabbitMQ, Celery is a small step. If you do not want to run workers, serverless plus a managed queue is simpler.

  • Cap concurrency per model and API key. A global cap is better than per-worker hope.

  • Retry only transient failures: timeouts, connection errors, rate limits, and 5xx responses. Do not retry auth or validation errors.

  • Make every job idempotent with a job_id. At-least-once delivery is the norm, not the exception.

  • Use deepseek-v4-flash for bulk work and deepseek-v4-pro for hard reasoning. Route by task type, not by habit.

  • Do not put interactive streaming chat behind an async queue. Stream in the request path; use queues for batch, enrichment, and background agent steps.

Provider access and pricing, without the spreadsheet

If you are building outside China and do not want to manage Chinese phone or bank requirements, AiCredits sells DeepSeek API credits with card or PayPal. The API is OpenAI-compatible, so the code above only changes base_url and the API key. Pricing is qualitative: off-peak usage costs less than peak, cache hits are cheaper than fresh tokens, and deepseek-v4-pro costs more than deepseek-v4-flash. Check aicreditsapi.com/deepseek-prices for current rates before you size a queue.

This matters for queue design because retries and duplicate work have a real cost. A good queue reduces wasted calls; a bad one multiplies them.

Serverless functions are not a queue. Celery is not a serverless platform. Pick the queue first, then the compute.

FAQ

Is Celery or serverless better for LLM jobs?

Neither wins universally. Celery wins when you need long-lived workers, custom routing, and tight concurrency control. Serverless wins when traffic is spiky and you want low ops, provided you put a real queue and concurrency cap in front.

Can I use serverless functions without a queue?

You can, but you lose retries, backpressure, and a dead-letter queue. For LLM calls that can time out or hit rate limits, a managed queue is the safer default.

How should I handle rate limits?

Cap concurrency per API key and model, add jitter to retries, and separate transient errors from terminal ones. Both Celery and serverless can do this; the difference is where the cap lives.

When should I use deepseek-v4-pro instead of deepseek-v4-flash?

Use flash for high-volume extraction, summaries, and classification. Use pro for harder reasoning or higher-stakes outputs, and route those jobs to a separate queue so bulk work does not starve them.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×