My third merged Serverless Land PR: semantic search with Bedrock and DynamoDB
A technical walkthrough of API contracts, embeddings, DynamoDB vector indexes, IAM, deployment, and testing—plus a practical guide to contributing a Serverless Land pattern.
PR #3275 has been merged into
aws-samples/serverless-patterns . It is my third merged contribution to this repository, following patterns for Cognito user provisioning and authenticated access to Amazon Bedrock through AppSync.This article walks through the new semantic-search implementation, its deployment boundaries, and the process another builder can follow to contribute a pattern. The source code and README are the reference implementation.
1. The problem this pattern solves
An application may need to find documents whose meaning matches a question even when the words differ. For example, a query about “finding embeddings without another database” should be able to retrieve a document describing native vector search.
If the application already stores its documents in DynamoDB, using an external vector store introduces another copy of the data and a synchronization path to operate. DynamoDB vector indexes allow embeddings to be stored with the document attributes and searched directly.
This sample connects that capability to two HTTP endpoints. Bedrock generates embeddings; DynamoDB retrieves matching documents. The response contains documents and distance scores. Adding answer generation or a complete RAG workflow would be a separate extension.
2. Architecture and request flow
The runtime has four AWS services:
Client → API Gateway HTTP API → Lambda ├→ Bedrock: generate embedding └→ DynamoDB: PutItem / SearchVectorsAWS CDK defines the infrastructure in TypeScript, and CloudFormation provisions the table and native vector index. Both endpoints share one application Lambda function.
Operation | API route | Processing | Success response |
|---|---|---|---|
Ingest a document | POST /documents | Validate → embed content → PutItem | HTTP 201 with the document ID |
Search documents | POST /search | Validate → embed query → SearchVectors | HTTP 200 with query and results |
The model is Amazon Titan Text Embeddings V2,
amazon.titan-embed-text-v2:0 . Documents and queries use normalized, 1,024-dimensional embeddings. The index uses cosine distance, so lower returned scores indicate closer matches.The Lambda uses Node.js 22 on ARM64, 512 MB of memory, and a 30-second timeout in this sample. Those settings describe the implementation; they are not a performance benchmark or a sizing recommendation for another workload.
3. Document keys and vector-index schema
A stored item contains the following attributes:
Attribute | Purpose |
|---|---|
tenantId | Table partition key and vector-index partition key |
documentId | Table sort key; identifies a document within its tenant |
title , content | Source text returned to the caller |
category | Required on ingestion; optional equality filter during search |
embedding | Numeric vector generated from the content |
createdAt | Timestamp written during ingestion |
The composite key is
(tenantId, documentId) . Two tenants can therefore use the same document identifier without overwriting each other's table item. Ingesting the same pair again replaces that item because the sample uses PutItem without a conditional expression.The vector index is named
document-embedding-index . Its vector attribute is embedding , its dimension count is 1,024, and its search schema contains:-
tenantIdas aHASHelement, required for the sample's searches.
-
categoryas anINLINE_FILTERelement for optional equality filtering.
- An
INCLUDEprojection containingtitleandcontent. Table keys and inline-filter attributes are available automatically.
The table uses on-demand capacity and explicitly configures
TableEncryption.AWS_MANAGED .4. Provisioning the index through CloudFormation
Review feedback helped simplify the infrastructure. The merged revision declares the index using the native
VectorIndexes property on AWS::DynamoDB::Table , rather than a custom-resource provider and additional Lambda functions.The CDK version pinned by the sample predates that property in its construct schema. The stack obtains the underlying
CfnTable and applies a property override. This is the relevant declaration from lib/vector-search-stack.ts :cfnTable.addPropertyOverride("VectorIndexes", [ { IndexName: VECTOR_INDEX_NAME, VectorAttribute: { AttributeName: "embedding" }, Dimensions: VECTOR_DIMENSIONS, DistanceFunction: "COSINE", SearchSchema: [ { AttributeName: "tenantId", SearchSchemaElementType: "HASH" }, { AttributeName: "category", SearchSchemaElementType: "INLINE_FILTER" }, ], Projection: { ProjectionType: "INCLUDE", NonKeyAttributes: ["title", "content"], }, },]);The stack also declares
tenantId , documentId , and category in AttributeDefinitions . Copying only the index override would omit part of the table declaration required by this implementation.The pinned CDK validation schema can warn that
VectorIndexes is unexpected. The PR records validation against the live CloudFormation resource schema. Check the CloudFormation vector-index reference when changing the declaration.Index properties cannot be updated in place. CloudFormation permits creating or deleting one vector index per stack operation. For replacement, add a differently named index in one deployment, switch the application and its IAM permission to the new index, and remove the old index in another deployment.
5. Calling the API
An ingestion request supplies all five document fields:
{ "tenantId": "tenant-1", "documentId": "doc-1", "title": "DynamoDB vector search", "content": "DynamoDB supports similarity search over embeddings stored with application data.", "category": "aws"}A search request uses the same tenant scope, with an optional category and result count:
{ "tenantId": "tenant-1", "query": "How can I search embeddings without a separate vector database?", "category": "aws", "topK": 5}The handler defaults
topK to five and accepts integers from 1 through 100. A minimal tenant-scoped SDK request has this shape; the complete handler adds a category condition when supplied:new SearchVectorsCommand({ TableName: requiredEnvironmentVariable("TABLE_NAME"), IndexName: requiredEnvironmentVariable("VECTOR_INDEX_NAME"), SearchVector: embedding.map(value => ({ N: String(value) })), TopK: request.topK ?? 5, SearchConditionExpression: "#tenantId = :tenantId", ExpressionAttributeNames: { "#tenantId": "tenantId" }, ExpressionAttributeValues: { ":tenantId": { S: request.tenantId } }, ProjectionExpression: "documentId, title, content, category",});This is an excerpt inside a handler with validated input and a generated
embedding , not a standalone program. The low-level DynamoDB client expects AttributeValue objects, including numeric values represented as { N: "..." } . See the SearchVectors API reference .6. Validation, permissions, and operational limits
Validation happens before Bedrock or DynamoDB calls. The handler rejects missing or malformed JSON, non-object bodies, empty required strings, invalid
topK values, and fields exceeding its configured limits. It checks tenant IDs against 2,048 UTF-8 bytes and document IDs against 1,024 UTF-8 bytes. Content and query input are capped at 50,000 characters; Bedrock's model and request limits still apply.The handler returns HTTP 400 for request-validation errors, HTTP 404 for an unrecognized route key, and a generic HTTP 500 for other failures. It checks that the returned embedding length matches the configured dimension count before storing or searching it.
The application data permissions are scoped as follows:
Action | Resource scope |
|---|---|
dynamodb:PutItem | The sample's document table |
dynamodb:SearchVectors | The named vector-index ARN |
bedrock:InvokeModel | The selected foundation-model ARN |
The API is intentionally unauthenticated, and its sample CORS policy allows all origins. Before using it with real tenant data, add an authorizer, derive the tenant scope from verified identity, and restrict allowed origins. A caller-supplied
tenantId is a filter, not proof of access to that tenant.Table-to-index synchronization is asynchronous. A newly written item might not appear in an immediate search. Test with a bounded retry or a short delay instead of assuming that HTTP 201 guarantees immediate search visibility.
The final native-index revision's recorded validation includes build, unit tests, synthesis, and CloudFormation schema checks. It was not live-deployed during that validation. Earlier live checks of a custom-resource revision do not validate the final provisioning path.
7. Deploy and exercise the sample
Use Node.js 22 or later, configured AWS CLI credentials, a CDK-bootstrapped account and Region, and access to the selected Bedrock model. Deploying creates billable resources. The example's removal policies delete its table and log group during cleanup, so use disposable test data.
git clone https://github.com/aws-samples/serverless-patterns.gitcd serverless-patterns/apigw-http-api-lambda-bedrock-dynamodb-vector-search/typescript/cdknpm installnpm run buildnpm testnpm run synthnpx cdk bootstrapnpx cdk deployRead
ApiEndpoint from the stack outputs and set API_ENDPOINT to that value. Then ingest a document:curl -X POST "${API_ENDPOINT}/documents" \ -H 'content-type: application/json' \ -d '{"tenantId":"tenant-1","documentId":"doc-1","title":"Vector search","content":"DynamoDB stores embeddings with application data.","category":"aws"}'After the item has propagated to the index, search it:
curl -X POST "${API_ENDPOINT}/search" \ -H 'content-type: application/json' \ -d '{"tenantId":"tenant-1","query":"Search embeddings with my application data","category":"aws","topK":5}'Test more than the successful path: omit a required field, submit malformed JSON, try an out-of-range
topK , use another tenant ID, and apply a category that should not match. Verify the response status and the documents returned. Testing a tenant filter does not validate an authorization layer that the sample does not implement.Delete the example resources when finished:
npx cdk destroy8. How to contribute a Serverless Land pattern
Start with the repository's current publishing guide and contribution guidelines . The following workflow summarizes their requirements and adds practical validation advice.
Choose a focused contribution
Search existing patterns, issues, and open or recently merged PRs first. If the same service integration already exists, contribute a language or framework variant within its family rather than creating a duplicate. Discuss significant work in an issue before investing in implementation.
A new pattern should demonstrate infrastructure as code for a focused integration of two to four AWS services with minimal custom code. You can also contribute a reproducible bug fix, clearer testing instructions, or another improvement to an existing pattern.
Fork, synchronize, and create a branch
Fork the repository in GitHub first. Replace
YOUR_GITHUB_USERNAME and the example branch name below with your own values:git clone https://github.com/YOUR_GITHUB_USERNAME/serverless-patterns.gitcd serverless-patternsgit remote add upstream https://github.com/aws-samples/serverless-patterns.gitgit fetch upstreamgit switch -c yourname-feature-my-pattern upstream/mainHere,
origin is your fork and upstream is the AWS sample repository. Start from the latest upstream main and keep one pattern variant in each PR.Use the current folder and metadata conventions
New variants use lowercase
{family}/{language}/{framework} folders. The current path for this contribution is:apigw-http-api-lambda-bedrock-dynamodb-vector-search/└── typescript/ └── cdk/ ├── README.md ├── example-pattern.json ├── bin/ ├── lib/ ├── src/ └── test/Use
_pattern-model or a similar variant as your starting point. Update copied service names, resource names, authors, framework, language, and deployment commands. Keep the template README sections and provide requirements, deployment, behavior, testing, and cleanup instructions.example-pattern.json builds the Serverless Land pattern page. Use official AWS service names on first mention in its title, keep that title within 100 characters and its description within 175, and choose supported schema values for language, framework, and level. gitHub.template.templateFile must point to the infrastructure file relative to the variant folder, such as lib/vector-search-stack.ts .Leave out secrets, account-specific outputs,
node_modules , and generated build output. The current publishing guide also asks contributors to leave architecture diagrams out of submissions; the Serverless Land team creates them.Validate the metadata and implementation
From the repository root, install the validator's dependencies and check your variant. Set
PATTERN_DIR to the actual folder you are contributing:PATTERN_DIR="your-family/typescript/cdk"(cd _scripts && npm install)node _scripts/validate.js "${PATTERN_DIR}/example-pattern.json"The repository validator also checks for admin-equivalent IAM grants. Scope actions and resources to the integration instead of granting administrative policies or unrestricted actions.
For a TypeScript CDK variant that defines the same npm scripts as this sample, run:
cd "$PATTERN_DIR"npm installnpm run buildnpm testnpm run synthUse the corresponding validation commands for another framework. Add tests for the actual behavior and infrastructure properties: request errors, filter construction, model/vector compatibility, encryption, and IAM scope. Before opening a PR, the publishing guide asks you to deploy and test in your own account. Verify the exact revision you plan to submit and exercise cleanup as well.
Record what you actually tested: commands, tool versions, deployment Region, successful and negative scenarios, and any remaining limitations. Keep credentials and account-specific identifiers out of that evidence.
Open the PR and stay involved
From the repository root, stage only your variant and push the branch:
cd "$(git rev-parse --show-toplevel)"git add "$PATTERN_DIR"git diff --cached --checkgit commit -m "Add a focused serverless integration pattern"git push -u origin yourname-feature-my-patternOpen a PR from your fork to upstream
main . Explain the integration, the problem it addresses, the files changed, and the validation performed. Complete the PR questions and required contribution/licensing statement. Review automated failures and respond to maintainer feedback with focused changes and updated test evidence.My own review is an example of why that last step matters: native CloudFormation index provisioning removed the custom-resource machinery, while explicit encryption and complete attribute definitions made the infrastructure declaration clearer.
9. The three contributions so far
Merged PR | Integration | What it demonstrates |
|---|---|---|
| #2704 | Cognito → Lambda → DynamoDB | Creating application user data after Cognito email confirmation |
| #2740 | Cognito → AppSync → Lambda → Bedrock | Authenticated GraphQL access to a Bedrock model |
| #3275 | API Gateway → Lambda → Bedrock + DynamoDB | Ingesting documents and retrieving semantic matches with native vector search |
Thank you to Marco (@marcojahn) and Julian Wood for their review and help getting the latest pattern merged. The merged PR , implementation , and publishing guide provide the detail needed to inspect the design or start a contribution of your own.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article