AWS Builder Center

Serendipity Engine: Building a Grounded "Constructive Surprise" Discovery App on AWS with the Events API, Amazon Bedrock, and Serverless Services

A technical write-up for the AWS re:Invent Event Catalog API Hackathon, built spec-first with Kiro.

Status note

This article describes the repository as it exists today. The code, infrastructure definitions and tests are written and pass locally. The stack has not been deployed to an AWS account, and no live session catalog has been ingested. The Events API's session endpoint returned  401  for anonymous calls during the spike, and the way a server-side job gets a token is not documented. Everything below is labeled accordingly. Where a claim could not be verified, it says so.



1. The problem

Conference catalogs are good at answering "show me sessions about X". They are less good at the question a curious attendee actually has: "what is a session I would never have searched for, but would be glad I found?"
Plain recommendation tends to return close neighbors. Pure randomness returns noise. Serendipity Engine aims for constructive surprise: a link between two sessions that is unexpected, but that you can defend by pointing at the text of the catalog.

2. What the solution is

Serendipity Engine finds "semantic bridges" between real AWS event sessions, explains each bridge using only cited catalog text, and assembles a 2 to 4 session discovery "quest".
A user enters one or two topics (for example, serverless and sustainability) and a novelty preference. The app returns:
  • Ranked bridges: pairs of sessions from different topic areas, with a score breakdown (relevance, bridge strength, novelty, diversity, quality).
  • Evidence: exact excerpts from session fields, kept visually separate from the AI's interpretation, plus an uncertainty statement.
  • A graph of topic and session nodes, with a list-view alternative.
  • A quest: an ordered 2 to 4 session path, with schedule conflicts flagged and unknown schedules marked as unknown.
  • An honest "no credible bridge" result when nothing passes the quality gates.
The core design rule is: deterministic core, generative edge. Retrieval, scoring, filtering, IDs, conflict detection and provenance are deterministic code. The language model only writes bounded prose, and its output is validated on the server. If validation fails or Bedrock is unavailable, a deterministic template explanation replaces it.

3. Architecture

3.1 Overview

The system is a TypeScript (strict) monorepo with these pieces:
Path
Purpose
 apps/web 
React + Vite UI
 services/api 
 /api/v1  handlers, route table, throttle policy
 services/ingestion 
Events API adapter, normalization, snapshots, publish gate, sync workflow
 services/indexer 
Bedrock embedding client, BM25 + vector index, SQS worker
 packages/contracts 
Shared Zod schemas, structured logger with redaction
 packages/discovery 
Retrieval, scoring, graph, explanation validator, quest planner
 packages/evaluation 
Labeled golden cases, metrics, threshold calibration
 infra/cdk 
AWS CDK v2 app (Data, Ingestion, Api, Web, Observability stacks)

3.2 Data flow


Ingestion path. An EventBridge Scheduler rule (hourly by default, and only enabled when an event ID is configured) or an operator call starts a Step Functions Standard workflow. The workflow pages through the Events API, stages raw pages in S3, normalizes records, quarantines malformed ones, builds an immutable snapshot manifest, enqueues only changed sessions (by content hash) to SQS for embedding, builds the index, runs completeness checks, and then publishes by switching  activeCatalogVersion  with a DynamoDB conditional write. A failure at any step leaves the active catalog unchanged.
Query path. A request goes through API Gateway to a Lambda. The Lambda loads the precomputed index for the active catalog version (cached per warm container), runs hybrid BM25 + vector retrieval, scores candidate bridges, applies hard gates and diversity reranking, and returns results with evidence. Explanations are generated lazily per bridge through Bedrock, validated, cached with a TTL, and replaced by a deterministic template if anything fails.

3.3 Key design decisions

The design recorded these decisions with their rationale:
Decision
Reason
REST adapter instead of calling the Events API from the browser
Protect credentials, control pagination, index locally
Deterministic ranking before the LLM
Reproducibility, grounding, lower cost
S3-hosted vector index for the MVP
Avoid a fixed idle cost from managed vector infrastructure
DynamoDB for metadata
Serverless on-demand access, conditional writes
Snapshot-based publication
Prevent partial catalogs from being exposed
Lazy explanation generation
Reduce token spend and latency
No attendee OAuth in the MVP
Reduce scope and privacy risk

3.4 Scoring

For a candidate bridge, the configurable initial scoring formula is:
score = 0.30*relevance + 0.25*bridgeStrength + 0.25*novelty + 0.15*diversity + 0.05*quality
All components are normalized to [0, 1]. Hard gates ( relevance >= R_min ,  bridgeStrength >= B_min , and at least two evidence items for a two-session bridge) apply regardless of the novelty setting. The novelty slider only reorders candidates that already passed the gates. The weights are initial configuration values and are not statistically validated.

4. AWS components used

All of the following appear in the CDK code under  infra/cdk/src  or in the service configuration.
Concern
AWS service
How it is used
Static hosting
Amazon S3 + Amazon CloudFront
Hosts the React build; a CloudFront response headers policy sets a CSP and other security headers
API
Amazon API Gateway (HTTP API)
Public discovery routes with per-route throttling; admin sync route uses  AWS_IAM  authorization
Compute
AWS Lambda (Node.js 22 runtime)
API handlers, ingestion, and the indexer worker
Metadata and cache
Amazon DynamoDB (on-demand)
Catalog metadata, active version pointer, feedback records and explanation cache with TTL
Snapshots and index
Amazon S3 (versioned, encrypted)
Staging pages, immutable snapshots, precomputed index
Orchestration
AWS Step Functions (Standard)
Catalog sync workflow with a catch-and-fail path
Scheduling
Amazon EventBridge Scheduler
Periodic sync
Queue
Amazon SQS + dead-letter queue
Embedding work items, retry isolation, KMS encryption
Embeddings and text
Amazon Bedrock
Titan Text Embeddings V2 (default) and a configurable text model
Secrets
AWS Secrets Manager
Events API credential, created empty and set by an operator
Encryption
AWS KMS
Customer-managed key for data resources
Observability
Amazon CloudWatch, Amazon SNS
Structured logs, custom metrics, alarms and a dashboard; SNS topic for alerts
Cost control
AWS Budgets
Monthly budget filtered by tag (created only when an alert email is supplied)
Infrastructure as code
AWS CDK v2 (TypeScript)
Five stacks: Data, Ingestion, Api, Web, Observability
CI/CD identity
IAM OIDC (GitHub Actions)
Deploy roles with no static AWS keys
The default model IDs are  amazon.titan-embed-text-v2:0  (1024 dimensions) for embeddings and  anthropic.claude-3-5-haiku-20241022-v1:0  for text. These are configuration defaults. Whether they are available in a given account and region was not verified, and the README lists it as an open decision.
AWS WAF is not attached. AWS WAF cannot be associated with HTTP APIs, so abuse controls are per-route throttling, a strict CORS allowlist, schema validation, body size limits and IAM.

5. Best practices applied

Grounding and AI safety

  • Evidence before generation. The model sees only retrieved session records with immutable IDs and exact excerpts, and a fixed JSON output schema.
  • Server-side validation. Cited session IDs must belong to the supplied evidence set, every excerpt must be a substring of the cited field, at least two sessions must be cited (or a single-session relationship declared), and an uncertainty statement is required.
  • Prompt injection posture. Session text is treated as untrusted data and the instruction says never to follow it as instructions.
  • Bounded failure. At most one retry, then a deterministic template. Model refusals, invalid JSON, timeouts and throttling all resolve to a valid explanation.
  • Honest "no match." If no candidate passes the gates, the API returns  noMatch: true  instead of inventing a bridge.
  • Reproducibility. Prompt version, model ID, embedding model, scoring configuration and catalog snapshot are recorded.

Data integrity

  • Snapshot-based publication. The active catalog version changes only through a DynamoDB conditional write after completeness and integrity checks. A partial snapshot is never activated, and the previous snapshot is kept.
  • Pagination discipline. The adapter follows  nextToken  until it is absent, even after short pages, stores tokens unchanged, detects repeated tokens and enforces a max-page guard.
  • Retries. Bounded exponential backoff with full jitter, honoring  Retry-After , only for 429 and 5xx. Permanent 4xx fails fast.
  • Idempotence. Content hashing means re-ingesting the same set produces the same result, and only changed sessions are re-embedded.
  • Never fabricate. Optional catalog fields stay absent when absent. Missing session times are shown as "unknown schedule", never as conflict-free.

Security

  • Least-privilege IAM. Separate roles for ingestion, indexer and API.  bedrock:InvokeModel  is scoped to the configured model ARNs. The API role has no Secrets Manager access and can only start the one sync state machine.
  • Allowlisted outbound host. The ingestion path calls only  api.awsevents.com .
  • No credentials in the browser or repository. Secrets live in Secrets Manager. Logs redact prompts, tokens and credential-like fields by default.
  • Encryption. KMS-encrypted S3, SQS and secrets, TLS enforced on the SNS topic.
  • Admin protection. The sync route requires  AWS_IAM  authorization.
  • CI/CD without static keys. GitHub Actions assume roles through OIDC, and deploys run from  main  behind environment approval.

Reliability and cost

  • SQS dead-letter queue with an alarm when it is not empty.
  • Fallbacks. Lexical-only retrieval if embeddings are unavailable, and a labeled last-known-good snapshot if the source is unavailable.
  • Cost-aware vector choice. An S3-hosted index loaded into Lambda memory avoids the fixed baseline of a managed vector collection. The README documents the comparison and when to switch (catalog or concurrency outgrowing Lambda memory, or cold start missing latency targets). That trade-off was not benchmarked.
  • Other controls. Explanation caching with TTL keyed by  (catalogVersion, bridgeId, promptVersion, modelId) , token caps, the strictest throttle on the explain route (5 rps, burst 10), a monthly budget and a daily Bedrock invocation alarm. AWS Budgets notifications are not hard spending caps.

Observability

  • Structured JSON logs with request IDs.
  • Alarms for catalog sync age, sync failures, failed Step Functions executions, API 5xx, API Lambda errors, API p95 latency, grounding validation failures and DLQ depth, among others.

Process

  • Spec-first development with Kiro. The project has requirements, a design with 20 formal correctness properties, and a dependency-ordered task plan under  .kiro/specs/serendipity-engine/ .
  • Strict TypeScript and shared runtime schemas (Zod) across the UI, API and services.
  • Spike before types. The Events API OpenAPI spec was fetched and analyzed before writing adapter types.
  • Pinned dependencies with a committed lockfile.

6. What went well

  • Spec-driven development kept the work coherent. Starting from requirements, then a design, then a task graph, made it possible to build a monorepo of many packages with clear boundaries. The final checkpoint passes: format, lint and typecheck are clean, and  npm test  runs 39 test files and 214 tests green.
  • The deterministic-core idea held up. Because the LLM is confined to a validated edge, the design could specify clear fallback behavior and clear properties for the parts that matter.
  • Grounding as a first-class rule. Validating excerpts as exact substrings, and checking cited IDs against an allowlist, turns "don't hallucinate" from a prompt wish into a testable check.
  • The API spike paid off early. Checking the live OpenAPI spec before coding showed real constraints:  sessionId  and  title  are the only required session fields, there is no URL field, and  ListSessions  needs authorization. The adapter and UI were designed around absent fields rather than assuming them.
  • Evaluation harness.  packages/evaluation  holds 22 labeled topic pairs (relevant, ambiguous, irrelevant, no-match, adversarial). On the committed run, with  R_min=0.3  and  B_min=0.25 , the README reports outcome accuracy of 95.5%, a false-bridge rate of 0.0%, a missed-bridge rate of 9.1%, and 100% programmatic grounding of evidence excerpts. Read these with the caveats in section 7.
  • Honest demo data. The committed offline snapshot has 14 fictional sessions and is labeled  OFFLINE SAMPLE DATA  ( live: false ), so it cannot be mistaken for the real catalog.

7. Lessons learned and current limitations

  1. Verify the data source before you design on it. The Events API session list was not available anonymously in the spike. Event endpoints worked, but  ListSessions  returned  401  with a bearer challenge, and the OpenAPI spec did not document how a server-side job would get a token (the protected-resource metadata advertised scope  events/access ). As a result, no authenticated payload has ever been seen. All session fixtures other than the observed event record and the 401 error are synthetic, and field mappings are based on the OpenAPI spec only. Doing the spike first meant this was discovered on day one rather than the day before the demo, but it still blocked live ingestion.
  1. "Code complete" is not "deployable." The CDK stacks default to an inline Lambda stub that throws "Lambda bundle not provided". There is no bundling step wired, and  main.ts  does not pass the code assets. This fail-loud behavior was deliberate, but it means a deploy would create infrastructure whose API and sync workflow fail until bundles are built. I would add a bundling task (for example with esbuild) to the plan from the start instead of at the end.
  1. Passing tests is not the same as verified behavior. The suite is green, but the plan marked most test-only sub-tasks as optional, and many were skipped. For example, the repository contains only a smoke test using  fast-check , so the 20 designed property tests are specified but largely not implemented. The  tests/integration  and  tests/e2e  workspaces are placeholders, so the CI jobs for them pass without exercising much. Property-based testing was a good fit for the pure logic layers, and I should have treated it as required rather than optional.
  1. Treat metrics as indicators. The evaluation set is small and synthetic, thresholds are not statistically validated, latency is measured in memory only, and the cost figure is a harness estimate. Human ratings for grounding (target 95%) and meaningful surprise (target 70%) were not collected. The performance targets (p95 under 5 s for discovery and 12 s for explanation) were not measured on a deployed stack.
  1. Cost choices are hypotheses until measured. The S3-hosted index is a reasoned trade-off for a short-lived demo. The raw float32 vectors for roughly 10,000 sessions at 1024 dimensions are about 40 MB, which seems plausible in Lambda memory, but cold-start time and 100-concurrent-explorer behavior were not benchmarked.
  1. Know the service limits. AWS WAF cannot be attached to an HTTP API. That led to relying on throttling, CORS, validation and IAM, and the README documents it rather than hiding it.
  1. Missing fields are the normal case. Venue, times and tags are all optional in the API, and there is no official deep-link field. Designing for absence (unknown schedule rather than conflict-free, links only if present) avoided a class of fabricated-data bugs.
  1. Unresolved questions to settle with the API owner. Licensing, caching and LLM-use terms for session content, credential acquisition for ingestion, tags mapping, Bedrock model and region availability, and judging and deployment restrictions remain open decisions in the README.

8. What I would do next

  • Add the Lambda bundling step and wire it into the CDK app, then deploy to a  dev  environment.
  • Resolve the Events API credential question, then run a real import and re-run the seed and evaluation against it.
  • Implement the designed property tests and the CDK assertion tests, and replace the integration and end-to-end placeholders.
  • Benchmark cold start, memory and concurrency of the S3-hosted index, and revisit the OpenSearch Serverless trade-off if targets are missed.
  • Run human evaluations of grounding and meaningful surprise.
  • Run accessibility checks with assistive technologies. The UI targets WCAG 2.2 AA, but conformance has not been verified.

9. Closing

The main idea of Serendipity Engine is simple: let deterministic code decide what is a defensible connection, and let the model only explain it, with every claim checked against the source. The architecture is serverless, uses managed AWS services, and keeps idle cost low. The honest status is that the design, code and local tests are in place, while live-data ingestion and deployment remain to be done.


References
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article