{"id":50870169,"url":"https://github.com/mikkopiu/lambda-deadline-middleware","last_synced_at":"2026-06-15T04:33:43.987Z","repository":{"id":364338653,"uuid":"1267184902","full_name":"mikkopiu/lambda-deadline-middleware","owner":"mikkopiu","description":"Zero-dependency AWS SDK v3 middleware that automatically propagates Lambda execution deadlines to outgoing SDK calls via AbortController-based timeouts","archived":false,"fork":false,"pushed_at":"2026-06-12T16:33:03.000Z","size":115,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-12T17:26:55.831Z","etag":null,"topics":["aws","aws-lambda","aws-lambda-node","aws-sdk","aws-sdk-v3","deadline","middleware","nodejs","smithy","timeout","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/lambda-deadline-middleware","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mikkopiu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-06-12T09:52:33.000Z","updated_at":"2026-06-12T16:09:03.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/mikkopiu/lambda-deadline-middleware","commit_stats":null,"previous_names":["mikkopiu/lambda-deadline-middleware"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/mikkopiu/lambda-deadline-middleware","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikkopiu%2Flambda-deadline-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikkopiu%2Flambda-deadline-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikkopiu%2Flambda-deadline-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikkopiu%2Flambda-deadline-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mikkopiu","download_url":"https://codeload.github.com/mikkopiu/lambda-deadline-middleware/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikkopiu%2Flambda-deadline-middleware/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34348291,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-15T02:00:07.085Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","aws-lambda","aws-lambda-node","aws-sdk","aws-sdk-v3","deadline","middleware","nodejs","smithy","timeout","typescript"],"created_at":"2026-06-15T04:33:43.418Z","updated_at":"2026-06-15T04:33:43.979Z","avatar_url":"https://github.com/mikkopiu.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003c!-- SPDX-FileCopyrightText: 2026 lambda-deadline-middleware contributors --\u003e\n\u003c!-- SPDX-License-Identifier: MIT --\u003e\n\n# lambda-deadline-middleware\n\nZero-dependency AWS SDK v3 middleware that automatically propagates Lambda execution deadlines to outgoing SDK calls via\n`AbortController`-based timeouts.\n\nWhen an AWS SDK call hangs inside a Lambda function, the runtime terminates the process at the configured timeout,\ndestroying in-flight OpenTelemetry/X-Ray spans without export. This library prevents that by computing per-request\ndeadlines from the Lambda's remaining execution time and aborting requests before the hard timeout fires.\n\n## Features\n\n- Automatic deadline propagation, no manual timeout configuration per call\n- Fresh deadline per retry: each SDK retry attempt uses _current_ remaining time\n- Signal composition: preserves caller-provided `AbortSignal` via `AbortSignal.any()`\n- Zero runtime dependencies (`@smithy/types` is compile-time only)\n- Complete no-op when no Lambda context is available\n- Optional OpenTelemetry span events on deadline aborts (detected dynamically)\n- Branded types prevent millisecond/buffer interchange at compile time\n\n## Requirements\n\n- Node.js ≥ 24\n- AWS SDK v3 (built against `@smithy/types` ≥ 3.0.0)\n\n## Installation\n\n```bash\npnpm add lambda-deadline-middleware\n```\n\n## Usage\n\nSetup requires two pieces:\n\n1. **Wrap your handler** with `withLambdaDeadline`. This stores the Lambda `context` (specifically\n   `getRemainingTimeInMillis()`) in `AsyncLocalStorage` so the SDK middleware can read it. The SDK middleware stack has\n   no access to the Lambda context on its own.\n\n2. **Register the middleware** on each SDK client via the standard `middlewareStack.use()` pattern.\n\n```typescript\nimport { withLambdaDeadline, deadlineMiddleware } from \"lambda-deadline-middleware\";\nimport { DynamoDBClient, GetItemCommand } from \"@aws-sdk/client-dynamodb\";\n\nconst dynamodb = new DynamoDBClient({});\ndynamodb.middlewareStack.use(deadlineMiddleware());\n\nexport const handler = withLambdaDeadline(async (event, context) =\u003e {\n  const result = await dynamodb.send(\n    new GetItemCommand({\n      /* ... */\n    }),\n  );\n  return { statusCode: 200, body: JSON.stringify(result) };\n});\n```\n\nEvery SDK call through `dynamodb` now receives a timeout derived from the Lambda's remaining execution time minus a\nconfigurable flush buffer (default: 1000ms).\n\n## How It Works\n\n```mermaid\nflowchart LR\n    subgraph Lambda Invocation\n        direction LR\n        A[Lambda Runtime] --\u003e B[withLambdaDeadline]\n        B --\u003e C[Your Handler]\n        C --\u003e D[SDK .send]\n    end\n\n    subgraph Per Attempt\n        direction LR\n        D --\u003e E[Deadline Middleware]\n        E --\u003e|getRemainingTimeInMillis\\nminus flush buffer| F[AbortController\\n+ setTimeout]\n        F --\u003e G[HTTP Request]\n    end\n\n    style E fill:#f9a825,stroke:#f57f17\n    style B fill:#66bb6a,stroke:#2e7d32\n```\n\n`withLambdaDeadline` stores the Lambda context in `AsyncLocalStorage`. The deadline middleware reads it on every attempt\n(including retries), computes a fresh timeout, and attaches an `AbortSignal` to the outgoing HTTP request.\n\n## Configuration\n\n### Flush Buffer\n\nThe flush buffer is subtracted from the remaining Lambda time to leave room for telemetry export and error handling:\n\n```typescript\n// Default: 1000ms\ndynamodb.middlewareStack.use(deadlineMiddleware());\n\n// Custom: 500ms\ndynamodb.middlewareStack.use(deadlineMiddleware({ flushBufferMs: 500 }));\n```\n\n### Telemetry\n\nIf `@opentelemetry/api` is installed, span events are emitted on deadline aborts. Disable with:\n\n```typescript\ndynamodb.middlewareStack.use(deadlineMiddleware({ telemetryEnabled: false }));\n```\n\n## Error Handling\n\nWhen remaining time is less than or equal to the flush buffer, the middleware throws `DeadlineExceededError` immediately\nwithout dispatching an HTTP request.\n\n```typescript\nimport { isDeadlineExceeded } from \"lambda-deadline-middleware\";\n\ntry {\n  await dynamodb.send(\n    new GetItemCommand({\n      /* ... */\n    }),\n  );\n} catch (error) {\n  if (isDeadlineExceeded(error)) {\n    console.log(`Deadline exceeded: ${error.deadlineMs}ms`);\n    console.log(`Remaining time was: ${error.remainingMs}ms`);\n  }\n  throw error;\n}\n```\n\n## Signal Composition\n\nIf you pass an `AbortSignal` to a request, the middleware composes both signals:\n\n```typescript\nconst controller = new AbortController();\nsetTimeout(() =\u003e controller.abort(), 5000);\n\nawait dynamodb.send(\n  new GetItemCommand({\n    /* ... */\n  }),\n  {\n    abortSignal: controller.signal,\n  },\n);\n```\n\n## API Reference\n\n### `withLambdaDeadline(handler, options?)`\n\nWraps a Lambda handler to store the Lambda context in `AsyncLocalStorage`. Required for the middleware to access\n`getRemainingTimeInMillis()`.\n\n```typescript\nfunction withLambdaDeadline\u003cTEvent, TResult\u003e(\n  handler: (event: TEvent, context: LambdaContextLike) =\u003e Promise\u003cTResult\u003e,\n  options?: DeadlineOptions,\n): (event: TEvent, context: LambdaContextLike) =\u003e Promise\u003cTResult\u003e;\n```\n\n### `deadlineMiddleware(options?)`\n\nReturns a `Pluggable` for `client.middlewareStack.use()`.\n\n```typescript\nfunction deadlineMiddleware(options?: DeadlineOptions): Pluggable\u003cobject, object\u003e;\n```\n\n### `getRemainingTimeInMillis()`\n\nAccessor for the current Lambda's remaining execution time. Returns `undefined` outside a Lambda context.\n\n```typescript\nfunction getRemainingTimeInMillis(): number | undefined;\n```\n\n### `isDeadlineExceeded(error)`\n\nType guard for deadline-triggered abort errors.\n\n```typescript\nfunction isDeadlineExceeded(error: unknown): error is DeadlineExceededError;\n```\n\n### `DeadlineExceededError`\n\n```typescript\nclass DeadlineExceededError extends Error {\n  readonly name: \"DeadlineExceededError\";\n  readonly deadlineMs: Milliseconds;\n  readonly flushBufferMs: FlushBufferMs;\n  readonly remainingMs: Milliseconds;\n}\n```\n\n### `DeadlineOptions`\n\n```typescript\ninterface DeadlineOptions {\n  readonly flushBufferMs?: number; // Default: 1000\n  readonly telemetryEnabled?: boolean; // Default: true\n}\n```\n\n### Types\n\n| Type                  | Description                                                                  |\n| --------------------- | ---------------------------------------------------------------------------- |\n| `Milliseconds`        | Branded number representing a duration in ms                                 |\n| `FlushBufferMs`       | Branded number for the flush buffer                                          |\n| `RequestDeadlineMs`   | Branded number for a computed deadline                                       |\n| `DeadlineComputation` | Discriminated union: `\"deadline\"` \\| `\"insufficient-time\"` \\| `\"no-context\"` |\n| `LambdaContextLike`   | Minimal interface: `{ getRemainingTimeInMillis?(): number }`                 |\n\n## Reporting Bugs\n\nFound a bug? Please open a [GitHub Issue](https://github.com/mikkopiu/lambda-deadline-middleware/issues/new) with:\n\n- Your Node.js version and AWS SDK version\n- A minimal code snippet reproducing the problem\n- Expected vs actual behavior\n\nFor security vulnerabilities, see [SECURITY.md](SECURITY.md) instead.\n\n## License\n\n[MIT](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmikkopiu%2Flambda-deadline-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmikkopiu%2Flambda-deadline-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmikkopiu%2Flambda-deadline-middleware/lists"}