Serverless · Freelance

Presigned-Upload Document Parsing API

SAM stack where a client requests a presigned S3 URL, uploads a PDF directly, and an S3-triggered Lambda parses it and stores computed results.

  • API Gateway
  • Lambda
  • S3 presigned URLs
  • DynamoDB
  • Lambda layers
  • SAM
  • Make

// Why this matters

A presigned S3 upload API is the right shape whenever users submit files that your backend must process: statements, invoices, forms, scans. Sending the file through API Gateway and Lambda caps you at small payloads, burns compute moving bytes, and complicates retries.

The business need in this project was straightforward: users upload a statement PDF and get structured, computed results back. The interesting engineering is everything around that: a safe way to hand out upload permission, a processing step that scales with uploads, and a clean contract for fetching results later.

This is the architecture I built for a freelance client, with domain-specific parsing replaced by a generic example. It is a good template for any upload then parse then compute workflow on serverless.

// The problem

API Gateway limits request bodies to a few megabytes, and Lambda to a similar synchronous payload size. A multi-page PDF often exceeds that, and base64 encoding inflates it further. Forcing uploads through the API leads to timeouts and ugly workarounds.

Parsing is also slow and variable. A PDF can take seconds to extract, and a burst of uploads should not block the caller. The work needs to be asynchronous with an ID the client can use to ask later.

Finally there is the trust boundary. You need to let an unauthenticated or lightly authenticated client write one object into your bucket, with a time limit and no ability to list or overwrite others. Opening the bucket is not an option.

// The solution

Split the flow into three Lambdas and one bucket. The first Lambda, behind POST /upload, validates the metadata, generates an ID, writes a record with status Uploading and returns a presigned PUT URL for a key derived from that ID. The client uploads directly to S3 with that URL. The second Lambda is triggered by the S3 object-created event, downloads the file to temporary storage, parses it, computes results and updates the record to Ready. The third, behind GET /results/{id}, reads the record.

Presigned PUT is simple but weak on constraints: it cannot limit the object size. If you need a size cap or content-type enforcement, use a presigned POST with conditions instead; the changes are small and shown in the pitfalls. Either way, derive the key from the server-generated ID, never from a client-supplied filename.

Dependencies like a PDF library are bulky, so they go in a Lambda layer shared by the parse function; the other two functions stay tiny. Packaging and deploys are driven by a Makefile (zip functions, upload to an artifacts bucket, deploy the stack) so any machine produces the same result.

The results endpoint is the part to get right. The original blocked in a loop waiting for the status to change; that wastes billed time and can hit the gateway timeout. A better contract is to return the record with its status and let the client poll, using HTTP 202 while processing. For a related audio flavour of the same asynchronous pattern, see Event-driven Call-Recording Transcoding and Transcription; for the upload half applied to video, see Serverless Video-on-Demand with MediaConvert, CloudFront and Cognito.

How it flows flow1. POST upload → 2. Direct upload → 3. S3 event → 4. Parse → 5. Calculate → 6. Store → 7. GET results01POST upload02Direct upload03S3 event04Parse05Calculate06Store07 · GATEGET results
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. POST uploadcreate an ID, save metadata, return a presigned URL
  2. Direct uploadclient PUTs the file straight to S3
  3. S3 eventobject-created invokes the parse Lambda
  4. Parseline parsers map text to a typed model
  5. Calculatehelpers produce results
  6. Storeresults written to the record
  7. GET results gateresults returned by ID
ClientAPIDynamoDBS3Parse LambdaPOST /upload with metadataput record status=Uploadingid and presigned PUT URLPUT pdf to the presigned URLObjectCreated eventstore results, status=ReadyGET /results/{id}
Upload and process. The file never touches API Gateway or the first Lambda.
APIAPI GatewayCORSPOST /uploadGET /results/{id}FunctionsgenerateUploadUrlparseDocumentgetResultsSharedPython layerTyped modelCalculatorDataUpload bucketResults table
Stack layers. Small functions, one heavy layer, one table, one bucket.

// Before you start

  • AWS SAM CLI 1.100+ and Docker (for building layers), plus Python 3.11.
  • An AWS account and a named CLI profile with CloudFormation, Lambda, S3, DynamoDB and IAM permissions.
  • An S3 bucket for build artifacts, separate from the upload bucket.
  • A sample PDF with text content (not a scan) for testing.
  • Basic familiarity with CloudFormation and IAM.

// Step-by-step implementation

  1. 01 Define the SAM template: bucket, table, API, three functions

    Use AWS::Serverless::Function with Events for the API routes and an S3 notification for the parser. Give each function its own least-privilege policy instead of one shared role with wildcard access; the original shared a broad role, which is the first thing to tighten.

    The bucket notification creates a circular dependency if the bucket references the function while the function permission references the bucket. Breaking it with an explicit permission resource and DependsOn is the standard fix.

  2. 02 The upload-URL function: validate, record, sign

    Generate the ID on the server, validate the metadata, write the record with status Uploading and an expiry, and sign a PUT URL for exactly one key. Keep the URL lifetime short (minutes). Bind the content type in the signature so a client cannot upload an executable under a PDF key.

    Write the record before returning the URL. If you did it afterwards, a fast client could upload and trigger the parser before the record exists.

  3. 03 A typed model and line parsers, kept out of the handler

    Parsing logic belongs in its own module with a typed model. Handlers stay thin and the parser is unit-testable without AWS. Use pdfplumber to extract text per page, then small regex-based line parsers that each fill one field. Each parser returns None when its pattern is absent, so a document with a missing field is detected rather than silently wrong.

    A dataclass for the model documents the contract. The same model is what you serialise into the results record.

  4. 04 The parse Lambda: S3 event in, results on the record out

    The handler reads the key from the event (URL-decoded), derives the ID from the filename, downloads to /tmp, parses, computes and updates the record. Use an update expression rather than read-modify-write so concurrent writers cannot clobber each other.

    Be deliberate about failure. If the file is unreadable or a field is missing, write status Error with a short reason so the client can tell the user, instead of leaving the record on Uploading until it expires.

  5. 05 A results endpoint that does not block

    Return the record with its status immediately. Use 200 with the result when Ready, 202 while processing and a clear error shape for Error. This removes the sleep loop, keeps the function cheap and puts the retry policy in the client where it belongs.

    DynamoDB returns numbers as Decimal, which json.dumps rejects; add a small encoder.

  6. 06 Build the layer and drive everything from a Makefile

    Binary dependencies must be built for the Lambda platform. Build the layer in a container with sam build so wheels match the runtime. The Makefile wraps build, upload and deploy so a new machine or a CI runner needs only the CLI and a profile.

  7. 07 Exercise the whole path from the command line

    Request an upload URL, PUT the sample file with the exact content type used in the signature, then poll the results endpoint until it returns 200. This is also the shape of an integration test in CI.

// How to verify it works

  • POST /upload returns 200 with a pdf_id and a URL; the DynamoDB record exists with status Uploading.
  • The PUT to the presigned URL returns 200 only with the matching content type; a wrong content type returns 403 SignatureDoesNotMatch.
  • CloudWatch shows one parse invocation per upload and the record changes to Ready with a result attribute.
  • GET /results/{id} returns 202 immediately after upload and 200 with results when processing is done; an unknown ID returns 404.
  • The uploaded object disappears after the lifecycle expiry and the record disappears after its TTL.

// Design decisions and trade-offs

  • Presigned upload avoids API payload limits and keeps files off the Lambda path.
  • Asynchronous, ID-keyed results pattern.
  • A layer for heavy dependencies; make-based reproducible deploys.

// Pitfalls and lessons learned

  • A presigned PUT cannot cap object size. If that matters, switch to presigned POST with a content-length-range condition, or validate size in the parse function and discard oversize files.
  • Browser uploads fail without an S3 CORS rule for PUT, even when API Gateway CORS is correct.
  • S3 event keys are URL-encoded. Decode before deriving the ID or the lookup misses on unusual filenames.
  • A synchronous wait loop in the results function wastes billed time and can exceed the gateway timeout. Return a status and let the client poll.
  • The notification and Lambda permission create a circular reference unless the permission is its own resource and the bucket depends on it.
  • Scanned PDFs return no text. Detect that case and report it; do not guess.

// Frequently asked questions

How do I upload large files through API Gateway and Lambda?

Do not send them through the API. Have a Lambda return a presigned S3 URL and let the client upload directly to S3, then process the file from the S3 event.

Presigned PUT or presigned POST?

PUT is simpler. POST lets you enforce a maximum size and content type with policy conditions, so use it when you must constrain uploads.

How should the client get results of asynchronous processing?

Return an ID at upload time and expose a results endpoint that reports status. Poll it, or push a notification when the status changes.

Why use a Lambda layer for the PDF library?

The library is large and only one function needs it. A layer keeps the other functions small and lets you update dependencies independently.

How do I secure the upload endpoint?

Put an authorizer on the API, keep URLs short-lived, bind the content type, derive the key on the server, and make the bucket private with a lifecycle rule.

// The outcome

Scalable document intake with no servers.

// Where to take it next

// Keep reading