Every millisecond counts when an AI coding assistant answers a developer’s question. Yet most teams still retrieve each secret one‑by‑one, unknowingly adding half‑a‑second of latency before the Lambda even starts handling Claude’s request. This post shows how to slurp multiple secrets in a single batch call and make your AI service feel instantaneous.
Why Secret Fetch Time hurts AI Lambdas
When a Lambda starts, it first runs the initialization phase (loading code, creating SDK clients, reading configuration). Only after that does it receive the first request. If during initialization you call Secrets Manager three times—once for a Claude API key, once for a vector‑DB token, and once for an S3 access key—each call adds network round‑trip time. In a typical VPC‑attached Lambda the round‑trip can be 150 ms ± 50 ms, so three calls easily exceed half a second.
In plain English: The Lambda spends almost as much time asking for passwords as it does answering the developer’s question.
Analogy
Imagine you are cooking a dish that needs three spices. If you run to the pantry three separate times, you waste time walking back and forth. If you grab all three spices in one trip, you start cooking sooner. The same principle applies to secret retrieval.
Naïve secret fetch (one‑by‑one)
// handler.ts – naive approach import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager"; const client = new SecretsManagerClient({}); // default config export const handler = async () => { // First secret const claudeResp = await client.send( new GetSecretValueCommand({ SecretId: "claude-api-key" }) ); const CLAUDE_KEY = claudeResp.SecretString!; // Second secret const vectorResp = await client.send( new GetSecretValueCommand({ SecretId: "vector-db-token" }) ); const VECTOR_TOKEN = vectorResp.SecretString!; // Third secret const s3Resp = await client.send( new GetSecretValueCommand({ SecretId: "s3-access-key" }) ); const S3_KEY = s3Resp.SecretString!; // ...use the three keys to talk to Claude, DB, S3 return { status: "ok" }; }; Each await pauses the initialization until the remote service answers. The code is easy to read but hurts performance.
Key takeaway: Serial secret calls add up, and that addition shows up before your Lambda can even process a user request.
Batch GetSecretValue: The API Explained
AWS Secrets Manager does not expose a single “batch” endpoint that returns many secrets at once. The service only offers GetSecretValue, which retrieves one secret per call. However, because the SDK is promise‑based, we can fire many GetSecretValueCommands at the same time and wait for all of them together. This is often called “parallel batching”.
Why parallel matters
When you start three network requests at once, the underlying TCP connections can be reused, and the total wall‑clock time becomes roughly the longest single request, not the sum of all three. In practice, a three‑secret batch finishes in ~150 ms instead of ~450 ms.
Tip: Parallel batching works only while you stay under the default quota of 10 GetSecretValue calls per second per account. Going beyond that triggers a
ThrottlingException.
Simple parallel batch example
import { SecretsManagerClient, GetSecretValueCommand, } from "@aws-sdk/client-secrets-manager"; const client = new SecretsManagerClient({}); /** * Retrieve any number of secret IDs in parallel. * Returns a map from secret name → secret value. */ async function batchFetch(secretIds: string[]): Promise<Record<string, string>> { // Create a command for each secret ID const commands = secretIds.map( (id) => new GetSecretValueCommand({ SecretId: id }) ); // Fire all commands at once; Promise.all resolves when every call finishes const responses = await Promise.all(commands.map((cmd) => client.send(cmd))); // Build a plain object: { "secret-id": "value", ... } const result: Record<string, string> = {}; responses.forEach((resp, idx) => { const id = secretIds[idx]; // SecretString contains the actual secret text; we assume it exists result[id] = resp.SecretString!; }); return result; } The function above hides the parallelism behind a clean interface. The next section shows how to add retry logic so that occasional throttling does not crash your Lambda.
Implementing a Batch Wrapper in Node.js with the AWS SDK v3
Below is a ready‑to‑copy helper that:
- Accepts an array of secret names.
- Calls
GetSecretValueCommandfor each name in parallel. - Retries any
ThrottlingExceptionwith exponential back‑off (wait 100 ms, then 200 ms, then 400 ms). - Returns a simple object
{ secretId: secretValue }.
// getMultipleSecrets.ts import { SecretsManagerClient, GetSecretValueCommand, SecretsManagerServiceException, } from "@aws-sdk/client-secrets-manager"; /** * Minimal exponential back‑off helper. * Waits `delay` milliseconds before resolving. */ function sleep(delay: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, delay)); } /** * Fetch many secrets with retry on throttling. * * @param secretIds - List of secret identifiers (ARN or friendly name) * @param maxRetries - How many retry attempts we allow (default 3) * @returns Mapping from secretId → secret string */ export async function getMultipleSecrets( secretIds: string[], maxRetries = 3 ): Promise<Record<string, string>> { const client = new SecretsManagerClient({}); // Helper that performs a single fetch with its own retry loop async function fetchWithRetry(id: string): Promise<string> { let attempt = 0; let backoff = 100; // start at 100 ms while (true) { try { const resp = await client.send( new GetSecretValueCommand({ SecretId: id }) ); // We assume the secret is stored as plain text (SecretString) return resp.SecretString!; } catch (err) { // Cast to the SDK's error type for easier inspection const awsErr = err as SecretsManagerServiceException; // If the error is throttling and we have retries left, back off and try again if (awsErr.name === "ThrottlingException" && attempt < maxRetries) { attempt++; await sleep(backoff); backoff *= 2; // exponential increase continue; } // For any other error or exhausted retries, re‑throw throw err; } } } // Kick off all fetches in parallel const promises = secretIds.map((id) => fetchWithRetry(id)); // Wait for every promise to settle; if one throws, the whole function rejects const values = await Promise.all(promises); // Assemble the result object const result: Record<string, string> = {}; secretIds.forEach((id, idx) => { result[id] = values[idx]; }); return result; } Using the wrapper inside a Lambda handler
// lambdaHandler.ts import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda"; import { getMultipleSecrets } from "./getMultipleSecrets"; // List the three secrets our Claude assistant needs const REQUIRED_SECRETS = [ "claude-api-key", "vector-db-token", "s3-access-key", ]; export const handler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { // ------------------------------------------------------------------ // 1️⃣ Fetch all secrets at once (initialization step) // ------------------------------------------------------------------ const secrets = await getMultipleSecrets(REQUIRED_SECRETS); // Destructure for readability const CLAUDE_KEY = secrets["claude-api-key"]; const VECTOR_TOKEN = secrets["vector-db-token"]; const S3_KEY = secrets["s3-access-key"]; // ------------------------------------------------------------------ // 2️⃣ Call Claude (pseudo‑code – replace with real SDK) // ------------------------------------------------------------------ // Imagine we have a function `callClaude` that needs the API key. // const completion = await callClaude(CLAUDE_KEY, event.body); // ------------------------------------------------------------------ // 3️⃣ Respond to the API Gateway request // ------------------------------------------------------------------ return { statusCode: 200, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: "ok" /*, completion */ }), }; }; All the heavy lifting happens once per cold start. Subsequent invocations reuse the same secret values because the Lambda container stays warm (unless you enable provisioned concurrency, which keeps containers hot even longer).
Tip: If your secrets rotate rarely, consider caching them in a global variable so that even warm invocations skip the SDK call entirely.
Measuring Init‑Time Improvements with a Real Claude Assistant
To prove that batching helps, we need a repeatable measurement. The trick is to capture the time from the moment the Lambda runtime begins executing your code (handler entry) until the first secret is ready.
Simple timer utility
// timer.ts export function startTimer(label: string) { const start = process.hrtime.bigint(); // high‑resolution nanoseconds return () => { const end = process.hrtime.bigint(); const ms = Number(end - start) / 1_000_000; // convert to milliseconds console.log(`${label}: ${ms.toFixed(2)} ms`); }; } Instrumented handler (naïve vs batched)
// benchmarkHandler.ts import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda"; import { startTimer } from "./timer"; import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager"; import { getMultipleSecrets } from "./getMultipleSecrets"; const client = new SecretsManagerClient({}); export const naiveHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { const stop = startTimer("Naïve init"); // three sequential fetches const a = await client.send(new GetSecretValueCommand({ SecretId: "claude-api-key" })); const b = await client.send(new GetSecretValueCommand({ SecretId: "vector-db-token" })); const c = await client.send(new GetSecretValueCommand({ SecretId: "s3-access-key" })); stop(); // log elapsed time // ...rest of the work return { statusCode: 200, body: "ok" }; }; export const batchedHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { const stop = startTimer("Batched init"); const secrets = await getMultipleSecrets([ "claude-api-key", "vector-db-token", "s3-access-key", ]); stop(); // log elapsed time // ...rest of the work return { statusCode: 200, body: "ok" }; }; Deploy both functions, invoke them a few times, and compare the logged numbers. A typical run in a VPC‑connected Lambda shows:
Naïve init: 542.31 ms Batched init: 158.74 ms That 380 ms difference is the time saved for every cold start. When your Lambda sits behind an AI coding assistant that must answer in under a second, the improvement can be the difference between “instant” and “slow”.
In plain English: Running the three secret calls together cuts the wait‑time by roughly two‑thirds, making the AI feel snappier.
Best Practices, Throttling Limits, and Gotchas
1. Respect the 10‑calls‑per‑second quota
If you run dozens of Lambdas at once, each making three parallel calls, you can exceed the account‑wide limit. Strategies:
- Add a tiny jitter to the back‑off delay (
Math.random() * 50) so retries don’t all line up. - Centralise secret access with a small “secret‑service” Lambda that caches results and serves other functions via HTTP.
2. Cache wherever possible
A global variable in the Lambda file scope lives across invocations while the container is warm. Example:
let cachedSecrets: Record<string, string> | null = null; async function ensureSecrets() { if (!cachedSecrets) { cachedSecrets = await getMultipleSecrets(REQUIRED_SECRETS); } return cachedSecrets; } 3. Handle rotation gracefully
Secrets can be rotated automatically (e.g., every 30 days). During the rotation window the new version may not be immediately available, causing a ResourceNotFoundException. Your retry logic should also catch this case and fall back to the previous version for a few seconds.
4. Mind the cost
- Secrets Manager charges $0.40 per secret per month. With 100 microservices you already spend $40 each month, regardless of call volume.
-
GetSecretValueitself is free, but the Lambda execution time you save translates to lower compute cost. - If you enable Provisioned Concurrency, you pay for always‑ready containers. Batching helps you make the most of those paid‑for seconds.
5. Cross‑account access
When a Lambda in Account A needs a secret stored in Account B:
- Resource policy on the secret must allow the IAM role from Account A.
- IAM policy attached to the Lambda’s role must also grant
secretsmanager:GetSecretValueon the ARN. - Missing either side results in an AccessDeniedException that looks like a network timeout.
6. VPC and SnapStart quirks
If your Lambda lives in a VPC, the network interface attachment is the dominant part of the cold start. Batching reduces only the Secrets Manager portion, not the VPC latency. SnapStart (which snapshots the initialized container) does not help when the container still needs a VPC ENI.
Key tip: Combine secret batching with warm‑up strategies (e.g., provisioned concurrency) for the biggest overall latency win.
The Takeaway
What you should remember after reading this article
- Serial secret calls add noticeable latency before any AI request can be processed.
- Parallel batching collapses multiple
GetSecretValuecalls into roughly the longest single request, shaving hundreds of milliseconds off cold starts. - A small wrapper (
getMultipleSecrets) with exponential back‑off protects you from the default 10 calls‑per‑second throttling limit. - Caching secrets in a global variable or a dedicated secret‑service Lambda eliminates repeat fetches for warm containers.
- Cost, rotation, cross‑account policies, and VPC attachment are all practical concerns that must be handled alongside batching.
Next steps you can take today
- Copy the
getMultipleSecretshelper into your project and replace any existing one‑by‑one secret fetches. - Add a simple cache (global variable) to keep secrets alive for warm invocations.
- Enable basic retry with exponential back‑off as shown; test throttling by artificially raising the call rate.
- Monitor CloudWatch metrics for
ThrottlingExceptionand Lambda cold‑start duration to verify the improvement. - Review your secret inventory and confirm you’re not paying for unused entries; prune or consolidate where possible.
By applying these steps, your Claude‑powered code‑completion service will start answering developers faster, keep the bill predictable, and stay resilient when the secret‑store throttles. Happy coding!
Transparency notice
This article was written with the help of an AI system — Groq (GPT OSS 120B).
Published: 2026-12-03 · Primary focus: SecretsManager
All code blocks are intended to be correct and runnable, but please verify them
against the official docs for the tools mentioned before using in production.Find an error? Drop a comment — corrections are always welcome.