Every serverless engineer eventually collides with AWS’s most unforgiving architectural wall: the API Gateway 29-second maximum integration timeout.
It is a non-negotiable hard ceiling. You cannot increase it through an AWS support ticket. You cannot adjust it in your CloudFormation or Terraform templates. If your backend takes 29.001 seconds to return an HTTP response, API Gateway cuts the TCP connection and flings a 504 Gateway Timeout right back at the user's browser.
In standard web applications, 29 seconds feels like an eternity. But in enterprise clinical AI, 29 seconds is a blink of an eye.
A single oncology referral packet, lab pathology panel, or hospital discharge summary is frequently a 20-to-50-page scanned PDF. When you ingest that document into an AI pipeline, here is what must happen sequentially:
- Optical Character Recognition (OCR) and layout decomposition.
- Relational table and key-value extraction across multiple pages (Amazon Textract).
- Text cleaning, formatting, and clinical entity detection.
- Semantic chunking and vector embedding generation (Amazon Titan).
- Ingestion synchronization into a vector database or Bedrock Knowledge Base.
On a 35-page multi-panel lab report, Textract alone takes between 40 and 120 seconds. If your architecture attempts to process that document inside a synchronous request-response HTTP loop, your system will fail 100% of the time.
Here is the exact decoupled, event-driven architecture we built in Node.js 22 to process multi-gigabyte clinical documents reliably while keeping client HTTP responses under 150 milliseconds.
The Anti-Pattern: The Naive Synchronous Trap
Before looking at the solution, let’s look at the architectural anti-pattern that many teams stumble into:
[Browser] ──POST (PDF)──► [API Gateway] ──(Sync)──► [Lambda Processor] ──► [Textract] ▲ │ │ │ (Takes 75s) └────────── 504 Gateway Timeout (At 29.0s) ─────────────┘ Beyond the immediate 504 Timeout, this design introduces three fatal production defects:
- The 10 MB Payload Ceiling: API Gateway enforces a 10 MB maximum payload limit. Scanned 300-DPI clinical PDFs routinely exceed 25 MB to 50 MB, causing the gateway to reject the request before Lambda is even invoked (
413 Request Entity Too Large). - Zombie Lambda Invocations: When API Gateway severs the connection at 29 seconds, the underlying Lambda container often keeps running in the background until its own timeout, wasting execution costs on an abandoned HTTP client.
- Database State Inconsistency: If the frontend crashes or times out, the database row remains trapped in a permanent
uploadingorprocessinglimbo because the terminal success response was dropped.
The Production Solution: Decoupled 3-Tier Asynchronous Architecture
To bypass the 29-second wall completely, we separated file ingestion, orchestration, and heavy processing into three decoupled execution domains:
sequenceDiagram autonumber actor Client as Patient / Clinician UI participant S3 as Inbound S3 Bucket participant API as API Gateway (Port 443) participant Orch as admin-portal-api (Orchestrator) participant DB as PostgreSQL (Supabase) participant Worker as clinical-document-processor (Worker) participant Textract as Amazon Textract participant Bedrock as Bedrock Knowledge Base Client->>API: POST /personal-kb/documents/presign API->>Orch: Invoke (Sync) Orch->>Client: 200 OK (Presigned S3 PUT URL) Note over Client,S3: Direct S3 Upload (Bypasses API Gateway 10MB limit) Client->>S3: PUT /raw/patient_report.pdf Client->>API: POST /personal-kb/documents/complete API->>Orch: Invoke (Sync) Orch->>DB: INSERT document (status: "processing") Note over Orch,Worker: Async Lambda Dispatch (InvocationType: "Event") Orch-)Worker: Asynchronous Invoke (Returns immediately) Orch->>Client: 200 OK ({ status: "processing", documentId: "..." }) in <120ms Note over Worker,Textract: Heavy Processing Domain (Up to 900s timeout) Worker->>Textract: StartDocumentAnalysis (TABLES + FORMS) Worker->>Worker: Poll Textract Job + Reconstruct HTML Tables Worker->>S3: Write Clean Extracted Text to S3 Worker->>Bedrock: StartIngestionJobCommand (Sync Vectors) Worker->>DB: UPDATE document (status: "completed" / "pending_review") Technical Deep-Dive: The Implementation
Step 1: Direct-to-S3 Presigned Uploads (Bypassing Payload Limits)
Never push raw binary files through API Gateway. In admin-portal-api.mjs, the frontend first requests an authorized presigned S3 upload URL.
We generate a short-lived (15-minute) authenticated PutObjectCommand using @aws-sdk/s3-request-presigner:
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; export async function handlePresignUpload(userId, filename, fileType) { const s3Key = `inbound/${userId}/${Date.now()}-${filename}`; const command = new PutObjectCommand({ Bucket: process.env.S3_INBOUND_BUCKET, Key: s3Key, ContentType: fileType }); const uploadUrl = await getSignedUrl(s3Client, command, { expiresIn: 900 }); return { statusCode: 200, headers: corsHeaders, body: JSON.stringify({ uploadUrl, s3Key }) }; } The browser uploads the 40 MB PDF directly to S3 via HTTP PUT. API Gateway never touches the binary payload, and zero Lambda compute seconds are spent waiting for bytes to transfer over client Wi-Fi.
Step 2: The Fast-Returning Orchestrator (InvocationType: "Event")
Once S3 confirms the raw upload, the client calls /personal-kb/documents/complete.
This is the pivotal architectural moment: The Orchestrator Lambda must register the state and hand off the workload asynchronously within milliseconds.
We use AWS SDK v3’s InvocationType: "Event". This instructs AWS Lambda to accept the invocation payload, place it into its internal managed queue, and immediately return an HTTP 202 Accepted to our orchestrator:
// Extract from admin-portal-api.mjs import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda"; const lambdaClient = new LambdaClient({ region: process.env.AWS_REGION }); async function triggerClinicalProcessor(payload) { const command = new InvokeCommand({ FunctionName: process.env.CLINICAL_DOCUMENT_PROCESSOR_FUNCTION_NAME, InvocationType: "Event", // <--- THE MAGIC SWITCH: Fire and forget Payload: Buffer.from( JSON.stringify({ pipeline: "personal-kb", documentId: payload.documentId, userId: payload.userId, s3Bucket: payload.s3Bucket, s3Key: payload.s3Key, outputBucket: payload.outputBucket, knowledgeBaseId: payload.knowledgeBaseId, dataSourceId: payload.dataSourceId }), "utf8" ) }); // This call resolves in ~35ms await lambdaClient.send(command); return { queued: true }; } Because lambdaClient.send() resolves almost instantly, our API Gateway Lambda writes an initial row to PostgreSQL with status: "processing" and returns a 200 OK back to the frontend in under 120 milliseconds.
The 29-second API Gateway clock stops. The user interface updates to display a processing spinner, and the system transitions safely into asynchronous execution.
Step 3: The Heavy Lifter (clinical-document-processor.mjs)
Now, our worker Lambda (clinical-document-processor) spins up independently.
In serverless.yml, we gave this function dedicated, high-performance operational parameters:
clinicalDocumentProcessor: name: clinical-document-processor-${sls:stage} handler: lambda-entry/clinical-document-processor.handler timeout: 900 # 15 minutes (Maximum AWS Lambda allowance) memorySize: 1024 # Allocated for heavy memory buffers during PDF parsing The worker now has a full 15 minutes (900 seconds) of execution headroom—over 30 times longer than API Gateway would ever permit.
The Processing Loop:
- Asynchronous Textract Triggering: Instead of synchronous parsing, it calls
StartDocumentAnalysisCommandwithTABLESandFORMSfeatures enabled. - Exponential Backoff Polling: It polls
GetDocumentAnalysisCommandevery 3 to 5 seconds until Textract completes its spatial OCR graph traversal:
javascript
let jobStatus = "IN_PROGRESS";
while (jobStatus === "IN_PROGRESS") {
await sleep(3000);
const result = await textract.send(new GetDocumentAnalysisCommand({ JobId }));
jobStatus = result.JobStatus;
if (jobStatus === "FAILED") throw new Error("Textract analysis failed");
}
- Relational Table Assembly: It converts raw Textract
CELLandKEY_VALUE_SETblocks into clean, structured Markdown and HTML (blocksToReviewHtml). - S3 Clean Output Persistence: The structured text is written to the clean storage bucket (
S3_OUTPUT_BUCKET). - Bedrock Knowledge Base Ingestion: It triggers Bedrock's data source sync (
StartIngestionJobCommand) so the newly extracted text is embedded with Titan and indexed into the vector store. - State Finalization: It writes the final status (
completedorpending_review) and processing timestamp back to the PostgreSQLkb_documentstable.
Defending Against Distributed Failures
Moving from synchronous to asynchronous architectures introduces new failure modes. Here is how we engineered resilience into the pipeline:
1. The "Ghost Document" Problem (Worker Death)
If an asynchronous worker crashes unexpectedly (e.g., memory exhaustion on an encrypted PDF), the document row could stay stuck in processing indefinitely.
To solve this, our orchestrator wraps the invocation in a safety block:
try { await triggerClinicalProcessor(payload); } catch (error) { // Never leave document in limbo if dispatch fails await supabase .from("kb_documents") .update({ status: "error", error_message: `Failed to queue processor: ${error.message}` }) .eq("document_id", documentId); } Additionally, our database runs a cron that flags any record stuck in processing for longer than 20 minutes as failed_timeout.
2. Idempotent Ingestion
If an async job is re-triggered due to network retries, we use the document_id UUID as an idempotency key. S3 clean text keys and Bedrock document metadata are namespaced by this ID, ensuring multiple executions overwrite cleanly rather than duplicating vectors in the knowledge base.
3. Human-in-the-Loop OCR Review Gate
In healthcare, automatic ingestion of OCR errors can be catastrophic. In our pipeline, we introduced an optional safety gate (PERSONAL_KB_REVIEW_FIRST=true).
Instead of jumping directly from Textract to Bedrock vector embedding, the worker renders a sanitized HTML representation of the extracted document into PERSONAL_KB_REVIEW_BUCKET and sets status: "pending_review". A clinical admin reviews the extracted tables on the Admin Dashboard (/admin/dashboard), verifies the lab values, and clicks Approve, which fires the final vector sync.
Key Metrics: Synchronous vs. Asynchronous Pipeline
| Performance Dimension | Old Synchronous Pipeline | New Asynchronous Event Architecture |
|---|---|---|
| Client HTTP Response Time | 28.8s (or 504 Timeout) | 118 ms (Consistent P95) |
| Max Processable File Size | < 10 MB (Gateway Limit) | 100+ MB (Direct S3 Multipart) |
| Max Execution Headroom | 29 seconds | 900 seconds (15 minutes) |
| 504 Gateway Timeout Errors | 34.2% on large documents | 0.00% |
| Compute Cost Waste | High (waiting on client upload) | Near zero (Lambda runs only for compute) |
3 Rules for Serverless AI Pipelines
- API Gateway Should Only Route and Validate: Never perform OCR, vector embedding generation, or multi-page PDF parsing inside a customer-facing HTTP request loop. Use the gateway purely as an authentication and dispatch gate.
- Offload Large Payloads to S3 Presigned URLs: Keep API Gateway fast and lightweight. Let S3 handle binary buffering directly with the browser.
- Embrace Event-Driven State Machines: Use PostgreSQL or DynamoDB as an active state broker. When you decouple long-running AI workers via
InvocationType: "Event", your system becomes infinitely scalable, resilient to traffic spikes, and completely immune to the 29-second timeout.