DEV Community

Dinesh_gowtham
Dinesh_gowtham

Posted on

How to Build a Claude‑Powered Code Suggestion Bot with DynamoDB Persistence, Explained Simply

Developers often lose the context of a conversation with an LLM as soon as a request finishes, forcing them to re‑send the whole history each time. By persisting prompt logs in DynamoDB you can give Claude a running memory without blowing up latency. This post shows exactly how to wire a GitHub webhook, Lambda, and DynamoDB together so your AI code assistant remembers what it suggested before.


Why DynamoDB Makes a Great Prompt Store

When a language model like Claude suggests a code change, you want to keep that suggestion around so the next request can build on it. Think of DynamoDB as a cheap, always‑on notebook that you can write a line to and later flip back to any page instantly.

Why a notebook, not a temporary chalkboard?

  • Durability – each entry lives until you delete it, surviving Lambda restarts.
  • Scalability – DynamoDB can store millions of prompt logs without you provisioning servers.
  • Fine‑grained reads – you can ask for “the last 10 items” without scanning the whole table.

In plain English: DynamoDB gives you a reliable place to stash each turn of the conversation, and you can pull exactly the bits you need when you need them.

Gotchas to keep in mind

  • The default read mode is eventual consistency: a write might not be visible for a fraction of a second. For a bot that needs the just‑written suggestion, you must either request a strongly consistent read or use a read‑after‑write pattern.
  • DynamoDB expects a primary key. We’ll use a composite key of conversationId (partition) and timestamp (sort) so prompts stay ordered.

Setting Up the Table for Immutable Prompt Logs

Why an immutable log?

Each prompt and response is a historical fact; you never want to overwrite it because the model may need to refer back to any point in the conversation. By making the log immutable we avoid accidental data loss and keep the ordering simple.

Create the table (AWS console or CLI)

aws dynamodb create-table \
  --table-name PromptLog \
  --attribute-definitions \
    AttributeName=conversationId,AttributeType=S \
    AttributeName=timestamp,AttributeType=N \
  --key-schema \
    AttributeName=conversationId,KeyType=HASH \
    AttributeName=timestamp,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST
Enter fullscreen mode Exit fullscreen mode
  • conversationId – a string that groups all prompts belonging to the same PR.
  • timestamp – a number (epoch ms) that orders entries chronologically.

TypeScript definitions for the table

// src/types.ts
/** Shape of a single prompt log entry */
export interface PromptLogEntry {
  /** The PR or conversation this entry belongs to */
  conversationId: string;
  /** Milliseconds since epoch – also acts as the sort key */
  timestamp: number;
  /** The user‑provided diff or request */
  userPrompt: string;
  /** Claude's reply – may be empty until we store it */
  assistantResponse?: string;
}
Enter fullscreen mode Exit fullscreen mode

Tip: Using a strongly typed interface helps the compiler catch mismatched attribute names before they hit DynamoDB.

Minimal DynamoDB client wrapper

// src/dynamoClient.ts
import { DynamoDBClient, PutItemCommand, QueryCommand } from "@aws-sdk/client-dynamodb";
import { PromptLogEntry } from "./types";

/** One client per Lambda execution is cheap; reuse it across invocations */
const client = new DynamoDBClient({});

/** Write a new log entry – we never overwrite an existing item */
export async function putPromptLog(entry: PromptLogEntry): Promise<void> {
  const cmd = new PutItemCommand({
    TableName: "PromptLog",
    Item: {
      conversationId: { S: entry.conversationId },
      timestamp: { N: entry.timestamp.toString() },
      userPrompt: { S: entry.userPrompt },
      // assistantResponse is optional at creation time
      ...(entry.assistantResponse && { assistantResponse: { S: entry.assistantResponse } })
    },
    // Condition ensures we don't clobber an existing entry with the same timestamp
    ConditionExpression: "attribute_not_exists(conversationId) AND attribute_not_exists(timestamp)"
  });

  await client.send(cmd);
}

/** Read the most recent N entries for a conversation */
export async function getRecentPromptLogs(
  conversationId: string,
  limit: number = 10
): Promise<PromptLogEntry[]> {
  const cmd = new QueryCommand({
    TableName: "PromptLog",
    KeyConditionExpression: "conversationId = :cid",
    ExpressionAttributeValues: {
      ":cid": { S: conversationId }
    },
    ScanIndexForward: false, // newest first
    Limit: limit,
    // Strongly consistent read avoids the eventual‑consistency pitfall
    ConsistentRead: true
  });

  const result = await client.send(cmd);
  // Map DynamoDB's AttributeValue shape back to our plain object
  return (result.Items ?? []).map(item => ({
    conversationId: item.conversationId.S!,
    timestamp: Number(item.timestamp.N!),
    userPrompt: item.userPrompt.S!,
    assistantResponse: item.assistantResponse?.S
  }));
}
Enter fullscreen mode Exit fullscreen mode
  • PutItemCommand writes a single immutable row.
  • ConditionExpression guarantees we never accidentally replace a prior log.
  • ConsistentRead: true forces DynamoDB to return the most recent write – the crucial fix for the eventual‑consistency gotcha.

Key takeaway: By using a composite primary key and a strongly consistent read, we get a reliable, ordered history that the bot can trust.

Lambda Handler that Calls Claude via fetch

Why a Lambda function?

A Lambda runs only when GitHub tells us there’s a new pull‑request diff. It gives us a cheap, automatically‑scaled compute container that can call Claude, read/write DynamoDB, and post a comment back to GitHub.

Expected event shape

GitHub sends a JSON payload with pull_request details. We only need the number (PR id) and the head.sha (latest commit).

Full handler code

// src/handler.ts
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
import { getRecentPromptLogs, putPromptLog } from "./dynamoClient";
import { PromptLogEntry } from "./types";

/** Claude endpoint – replace with your actual API key */
const CLAUDE_ENDPOINT = "https://api.anthropic.com/v1/completions";
const CLAUDE_API_KEY = process.env.CLAUDE_API_KEY!;

/** Helper: call Claude with a list of prior messages */
async function callClaude(messages: string[]): Promise<string> {
  const body = {
    model: "claude-3-5-sonnet-20241022",
    max_tokens: 1024,
    temperature: 0.2,
    // Claude expects an array of messages, each with role & content
    messages: messages.map((msg, i) => ({
      role: i % 2 === 0 ? "user" : "assistant",
      content: msg
    }))
  };

  const response = await fetch(CLAUDE_ENDPOINT, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": CLAUDE_API_KEY,
      "anthropic-version": "2023-06-01"
    },
    body: JSON.stringify(body)
  });

  if (!response.ok) {
    const txt = await response.text();
    throw new Error(`Claude error ${response.status}: ${txt}`);
  }

  const data = await response.json();
  // Claude returns the completion in `completion` field
  return data.completion as string;
}

/** Main Lambda entry point – triggered by API Gateway (GitHub webhook) */
export async function handler(
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> {
  // 1️⃣ Parse incoming webhook payload
  const payload = JSON.parse(event.body ?? "{}");
  const prNumber = payload.pull_request?.number;
  const repoFullName = payload.repository?.full_name;
  const commitSha = payload.pull_request?.head?.sha;

  if (!prNumber || !repoFullName || !commitSha) {
    return { statusCode: 400, body: "Missing PR information" };
  }

  // Build a deterministic conversation ID: repo#pr
  const conversationId = `${repoFullName}#${prNumber}`;

  // 2️⃣ Read the last 10 prompts (including prior Claude replies)
  const recentLogs = await getRecentPromptLogs(conversationId, 10);
  const priorMessages = recentLogs
    .sort((a, b) => a.timestamp - b.timestamp) // oldest → newest
    .flatMap(log => [
      log.userPrompt,
      log.assistantResponse ?? "" // empty string if not yet filled
    ]);

  // 3️⃣ Append the new diff as the latest user message
  const newDiff = payload.pull_request?.diff_url
    ? await fetch(payload.pull_request.diff_url).then(r => r.text())
    : "No diff available";
  const allMessages = [...priorMessages, newDiff];

  // 4️⃣ Ask Claude for a suggestion
  const suggestion = await callClaude(allMessages);

  // 5️⃣ Persist the new entry (user prompt + Claude response)
  const now = Date.now();
  const newEntry: PromptLogEntry = {
    conversationId,
    timestamp: now,
    userPrompt: newDiff,
    assistantResponse: suggestion
  };
  await putPromptLog(newEntry);

  // 6️⃣ Post the suggestion back to the PR as a comment
  const commentResponse = await postGitHubComment(repoFullName, prNumber, suggestion);

  return {
    statusCode: 200,
    body: JSON.stringify({ commentUrl: commentResponse.html_url })
  };
}

/** Minimal GitHub comment helper – uses a personal access token */
async function postGitHubComment(
  repo: string,
  pr: number,
  body: string
): Promise<any> {
  const token = process.env.GITHUB_TOKEN!;
  const url = `https://api.github.com/repos/${repo}/issues/${pr}/comments`;
  const resp = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `token ${token}`,
      "Content-Type": "application/json",
      "User-Agent": "claude-code-bot"
    },
    body: JSON.stringify({ body })
  });

  if (!resp.ok) {
    const txt = await resp.text();
    throw new Error(`GitHub comment failed ${resp.status}: ${txt}`);
  }
  return resp.json();
}
Enter fullscreen mode Exit fullscreen mode

Explanation of key steps

  1. Parse webhook – we extract enough identifiers to build a stable conversationId.
  2. Read recent logs – we ask DynamoDB for the last 10 entries using a strongly consistent read (ConsistentRead: true).
  3. Fetch the diff – GitHub provides a URL to the raw diff; we download it with fetch.
  4. Call Claude – we send the whole conversation as an array of messages.
  5. Persist – we store the user diff and Claude’s suggestion as one immutable row.
  6. Comment back – a simple POST to GitHub creates a comment visible to reviewers.

Tip: The ConditionExpression in putPromptLog prevents the rare case where two Lambda invocations try to write the same timestamp (unlikely, but safe).

Lambda SDK gotchas

  • The @aws-sdk/client-lambda package is only needed if you want to invoke other Lambdas from here. In this example we stay inside a single function, but keep the import ready for future extensions.
  • Remember to give the Lambda execution role permissions for dynamodb:PutItem, dynamodb:Query, and lambda:InvokeFunction (if you add cross‑Lambda calls).

Streaming New Code Changes with DynamoDB Streams

Why a stream?

Sometimes you want other services (e.g., a dashboard or a metrics collector) to react as soon as a new suggestion is stored. DynamoDB Streams provide a time‑ordered log of every change, similar to a river that carries each new pebble downstream.

Enable the stream on the table

aws dynamodb update-table \
  --table-name PromptLog \
  --stream-specification StreamEnabled=true,StreamViewType=NEW_IMAGE
Enter fullscreen mode Exit fullscreen mode
  • NEW_IMAGE means the stream record contains the full item after the write – perfect for our immutable log.

Minimal consumer Lambda (processes the stream)

// src/streamConsumer.ts
import {
  DynamoDBStreamEvent,
  DynamoDBRecord,
  Context as LambdaContext
} from "aws-lambda";

/** Example: send a metric to CloudWatch for every new suggestion */
export async function handler(
  event: DynamoDBStreamEvent,
  _context: LambdaContext
): Promise<void> {
  for (const record of event.Records) {
    // We only care about INSERT events (new logs)
    if (record.eventName !== "INSERT") continue;

    const newImage = record.dynamodb?.NewImage;
    if (!newImage) continue;

    const conversationId = newImage.conversationId.S!;
    const timestamp = Number(newImage.timestamp.N!);
    const assistantResponse = newImage.assistantResponse?.S ?? "";

    // Simple log – replace with any downstream action you need
    console.log(
      `New Claude suggestion for ${conversationId} at ${new Date(timestamp).toISOString()}:\n${assistantResponse}`
    );

    // Example: publish to an SNS topic, push to a WebSocket, etc.
    // await snsClient.publish({ ... }).promise();
  }
}
Enter fullscreen mode Exit fullscreen mode
  • The event contains an array of DynamoDBRecord objects, each representing a single write.
  • By focusing on INSERT, we ignore updates (there are none in our immutable design).

In plain English: DynamoDB Streams act like a notification bell that rings every time we add a fresh suggestion, letting other pieces of our system hear about it instantly.

Putting It All Together: End‑to‑End Bot Flow

  1. GitHub webhook fires on a pull‑request event → API Gateway forwards JSON to our Lambda.
  2. Lambda parses the PR, fetches the latest diff, reads the last 10 prompts from DynamoDB (strong consistency).
  3. Lambda builds a message list, calls Claude via fetch, receives a code suggestion.
  4. Lambda writes a new immutable entry to DynamoDB (PutItem with condition).
  5. DynamoDB Streams emit an INSERT record → Stream‑consumer Lambda logs or forwards the suggestion.
  6. Lambda posts the suggestion back to the PR as a comment, completing the user‑visible loop.

Architecture diagram (text version)

GitHub PR  ──► API GW ──► Lambda (handler) ──► DynamoDB (PromptLog)
                               │               ▲
                               │               │
                               ▼               │
                         Claude API            │
                               │               │
                               ▼               │
               (optional) Stream‑Consumer Lambda ◄─ DynamoDB Streams
Enter fullscreen mode Exit fullscreen mode

Key takeaway: The whole workflow lives on managed services; no servers to patch, no containers to manage. All state lives in DynamoDB, and the only moving part is the Lambda that coordinates the conversation.

The Takeaway

  • DynamoDB’s durable, ordered primary key makes it a natural place to store each turn of an LLM conversation.
  • Use strongly consistent reads (or a read‑after‑write pattern) to avoid the eventual‑consistency pitfall when you need the just‑written suggestion.
  • A single immutable write per turn, guarded by a ConditionExpression, protects against accidental overwrites.
  • Lambda can fetch the recent prompt history, call Claude with native fetch, and store the new reply – all in a few dozen lines of TypeScript.
  • Enabling DynamoDB Streams gives you an instant feed of new suggestions for analytics, dashboards, or downstream bots.
  • The entire stack (GitHub webhook → API Gateway → Lambda → DynamoDB → Claude) runs without provisioning servers, keeping cost low and scaling automatically.

Happy coding! 🎉


Transparency notice

This article was written with the help of an AI system — Groq (GPT OSS 120B).

Published: 2026-11-27 · Primary focus: dynamodb

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.

Top comments (0)