Skip to content
Visual explainer 3h to learn 5 steps

Accept a document and start an ingestion job

Accept validated uploads into object storage and return a job that clients can poll.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.

Topic 13 of 29

In short

An upload endpoint should do as little as possible while the client waits: check the file, store it in object storage, record a document and a job, and answer 202 Accepted. The slow work of reading, chunking and embedding happens later in a worker. The client then polls a job URL to see progress, so a large PDF never ties up a request for minutes.

Think of it like this: It is like handing a parcel in at a post office counter: you get a tracking number at once, and the sorting happens out of sight.

Explained simply

When someone uploads a document to an AI app, the app has a lot to do: read the file, pull out the text, cut it into pieces and turn each piece into numbers for search. That can take seconds or minutes. If the web request waited for all of it, the browser would sit there and proxies would often cut the connection.

So the upload endpoint does only the quick, safe part. It checks that the file is not too big and really is the type you allow. It saves the file in object storage, which is a service built for storing whole files. It writes two rows in the database: one for the document and one for a job that says the document still needs processing.

Then it answers straight away with status 202 Accepted. That code means: I have your request, but the work is not done. The reply includes a job ID and a link where the client can check progress.

The browser then polls, which means it asks the status link every few seconds. The answer moves from queued to running to succeeded or failed. A separate worker program does the slow work in the background. This split keeps the API fast and lets you retry processing without asking the user to upload again.

Press Play on a diagram to walk through it one step at a time.

SequenceUpload now, process later
Client
FastAPI
Object storage
Database
  1. 1POST /documents (multipart file)
    Client to FastAPI: POST /documents (multipart file)
  2. 2Checked file stored under tenant/doc_id key
    FastAPI to Object storage: Checked file stored under tenant/doc_id key
  3. 3Insert document and job (queued)
    FastAPI to Database: Insert document and job (queued)
  4. 4202 Accepted + job_id + Location
    FastAPI to Client: 202 Accepted + job_id + Location
  5. 5GET /jobs/{job_id} until done
    Client to FastAPI: GET /jobs/{job_id} until done
LayersWhere each piece of upload state lives
  1. 1
    Browser

    Selected file, upload progress, job ID to poll

  2. 2
    FastAPI

    Validation and the 202 contract; keeps no state between requests

  3. 3
    Object storage

    The original file bytes under tenant/doc key

  4. 4
    Postgres

    Document and job rows, status, checksum, attempts

  5. 5
    Worker

    Picks up queued jobs and updates their status

In depth

Validating size and type without trusting the client

FastAPI reads files with UploadFile, which needs the python-multipart package installed. UploadFile spools data to a temporary file once it passes about 1 MB, so it does not hold a big upload in memory. You still need a hard limit. Check file.size against your maximum and return 413 Content Too Large when it is over. Also limit the request body at the proxy (for example client_max_body_size in NGINX), because by the time your code runs the bytes have already arrived.

The file name and the Content-Type header come from the client and can say anything. Read the first few bytes and compare them to the real signature: %PDF- for PDF, PK for ZIP-based formats such as DOCX. Return 415 Unsupported Media Type for anything else. Never use the original file name as a storage path; it may contain ../ or odd characters. Keep it only as display metadata.

MapChecks before a file is accepted
Incoming upload
  • Size
    • Proxy body limit
    • file.size against maximum
    • 413 when too large
  • Type
    • Magic bytes, not the header
    • Allowlist of formats
    • 415 when not allowed
  • Caller
    • Authenticated user
    • Tenant from the token
    • Quota not exceeded
  • Name
    • Kept only as metadata
    • Never used as a path

Object storage and what goes in the database

Large binary files do not belong in Postgres rows. Put the bytes in object storage under a key you build yourself, such as tenant_id/document_id.pdf. Locally you can run MinIO, an S3-compatible server, or simply write to a folder behind the same small storage interface; in the cloud the same interface can wrap Amazon S3 or Azure Blob Storage. Object storage is a paid cloud service, but the local options cost nothing.

The database row for the document stores the IDs, the tenant, the original name, the size, a SHA-256 checksum, the storage key and a status. The checksum lets you spot the same file uploaded twice. Create the document row and the job row in one transaction so you never have a document with no job or a job with no document.

  • Bytes: object storage
  • Facts about the bytes: Postgres
  • Server-generated UUIDs for document and job
  • Checksum for duplicate detection

The 202 response and the status contract

A good 202 body gives the client everything it needs to continue: the document ID, the job ID, the current status and the URL to poll. Many APIs also set a Location header pointing at GET /jobs/{job_id}. Adding a Retry-After header suggests how many seconds to wait before polling.

The job resource should have a small, fixed set of status values that clients can switch on: queued, running, succeeded and failed. Include timestamps, the number of attempts and, on failure, a safe error code and message that do not leak internal details. Keep the shape stable so the frontend can show a progress state without guessing.

Paginating jobs and documents

A tenant may upload thousands of documents, so GET /documents and GET /jobs must never return everything. Offset pagination (limit and offset) is simple but gets slow on deep pages and can skip or repeat rows when new rows arrive. Cursor pagination is steadier: sort by a unique key such as (created_at, id), return the last value as an opaque cursor, and on the next call ask for rows after it.

Always cap the page size on the server, for example at 100, whatever the client asks for. Filter by tenant before paging, and put an index on (tenant_id, created_at, id) so each page is a fast index range scan.

CompareOffset versus cursor pagination
Offset
  • ?limit=20&offset=40
  • Easy to jump to page 3
  • Slow on deep pages
  • Rows can shift between calls
Cursor
  • ?limit=20&after=opaque-token
  • Next and previous only
  • Same speed on every page
  • Stable while new rows arrive

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Validate file size and type~35m
  2. 2
    Store the file in object storage~35m
  3. 3
    Create document and job IDs~35m
  4. 4
    Return 202 Accepted~35m
  5. 5
    Paginate job status~35m

Key points

  • Validate size and type on the server; the browser's content type is only a hint.
  • Store the bytes in object storage and keep only metadata and the storage key in Postgres.
  • Generate document and job IDs on the server and return them with 202 Accepted.
  • Give clients a status URL to poll, and paginate any list of jobs or documents.
  • Every record carries the tenant ID taken from the auth token, never from the request body.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
@router.post('/documents', status_code=202)
async def upload(file: UploadFile, user: User = Depends(current_user)):
    if file.size is None or file.size > MAX_BYTES:
        raise HTTPException(413, 'File too large')
    head = await file.read(5)
    if head != b'%PDF-':
        raise HTTPException(415, 'Only PDF files are accepted')
    await file.seek(0)
    doc_id, job_id = uuid4(), uuid4()
    key = f'{user.tenant_id}/{doc_id}.pdf'
    await storage.put(key, file.file)
    await repo.create_document_and_job(user.tenant_id, doc_id, job_id, key)
    return {'document_id': doc_id, 'job_id': job_id, 'status': 'queued'}

Validate, store, record, answer 202. No parsing or embedding inside the request.

A user uploads a 3 MB PDF

Step 1: the browser sends POST /documents as multipart form data with a bearer token. Step 2: FastAPI resolves the user and tenant from the token. Step 3: file.size is 3 MB, under the 20 MB limit, and the first bytes are %PDF-. Step 4: the file is written to tenant-a/7f3c.pdf in MinIO. Step 5: one transaction inserts the document row and a job row with status queued. Step 6: the API answers 202 with the IDs and a Location header. The whole request takes well under a second.

bash
curl -i -X POST http://localhost:8000/documents \
  -H 'Authorization: Bearer <demo-token>' \
  -F 'file=@./samples/handbook.pdf;type=application/pdf'

# HTTP/1.1 202 Accepted
# location: /jobs/2b1e...
# {"document_id":"7f3c...","job_id":"2b1e...","status":"queued"}

Polling the job with a cursor-paginated list

The UI polls GET /jobs/{job_id} every two seconds and stops at succeeded or failed. The documents page lists the tenant's uploads 20 at a time. The server returns next_cursor, built from the last row's created_at and id. The client sends it back as after= to load the next page. If a request asks for limit=500, the server quietly caps it at 100.

python
@router.get('/documents')
async def list_documents(limit: int = Query(20, le=100), after: str | None = None,
                         user: User = Depends(current_user)):
    cursor = decode_cursor(after) if after else None
    rows = await repo.list_documents(user.tenant_id, limit + 1, cursor)
    page, more = rows[:limit], len(rows) > limit
    nxt = encode_cursor(page[-1].created_at, page[-1].id) if more else None
    return {'items': page, 'next_cursor': nxt}

Quick reference

  • pip install python-multipart before using UploadFile or Form in FastAPI.
  • 413 = too large, 415 = unsupported type, 202 = accepted, work continues.
  • Check magic bytes: %PDF- for PDF, PK for DOCX and other ZIP-based files.
  • Storage key = tenant_id/document_id.ext; never the client's file name.
  • Insert the document and job rows in one transaction.
  • Return job_id plus a Location header pointing at GET /jobs/{id}.
  • Cap page size on the server and index (tenant_id, created_at, id).

Common mistakes

  • Calling await file.read() on the whole upload and keeping it in memory, which lets one large file exhaust the server.
  • Trusting the file name or Content-Type header from the client instead of checking the bytes.
  • Returning 200 with the finished result for slow work, so requests time out behind proxies.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why should the upload endpoint not extract and embed the document before replying?

Question 2

2A client sends a file named report.pdf with Content-Type application/pdf, but its first bytes are MZ. What should happen?

Question 3

3Where should the tenant ID for a new document come from?

Question 4

4What is the main advantage of cursor pagination over offset pagination?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write the JSON body and headers your POST /documents endpoint returns, and list the four job status values a client may see.

  2. Exercise 2medium

    Add a size check and a magic-byte check to an UploadFile endpoint that allows PDF and DOCX up to 20 MB. Test it with a real PDF and a renamed text file.

  3. Exercise 3hard

    Make uploads safe to retry: if the same tenant uploads a file with the same SHA-256 checksum, return the existing document and job instead of creating new ones.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use 201 Created or 202 Accepted for uploads?
Use 201 when the resource is complete when you reply. If processing continues in the background, 202 is clearer because it tells the client to check back.
Can I store uploaded files directly in Postgres?
Postgres can hold binary data in a bytea column, but large files bloat backups and slow queries. Object storage is cheaper and built for it; keep the key in Postgres.
How often should the client poll the job?
Every one to five seconds is typical for interactive uploads, with a growing delay for long jobs. Honour a Retry-After header if the server sends one.
Do I need S3 or Azure to follow along?
No. Run MinIO in Docker, or write to a local folder behind the same storage interface, and swap in a cloud store later.

Go deeper

ShareXLinkedInWhatsApp