Use Cases

AWS Lambda-Optimierung mit Claude Code

Erfahren Sie mehr über AWS Lambda-Optimierung mit Claude Code. Praktische Tipps und Codebeispiele inklusive.

AWS Lambda-Entwicklung mit Claude Code beschleunigen

AWS Lambda ist ein ereignisgesteuerter Serverless-Computing-Service. In enger Zusammenarbeit mit AWS-Services wie API Gateway, S3 und DynamoDB können skalierbare Backends erstellt werden. Mit Claude Code lassen sich Lambda-spezifische Implementierungsmuster und IaC-Code effizient schreiben.

Grundlegendes Lambda-Funktionsdesign

> Erstelle eine Lambda-Funktion in TypeScript.
> Konfiguriert für die Verarbeitung von Anfragen über API Gateway.
// src/handlers/api.ts
import {
  APIGatewayProxyEvent,
  APIGatewayProxyResult,
  Context,
} from 'aws-lambda';

export const handler = async (
  event: APIGatewayProxyEvent,
  context: Context
): Promise<APIGatewayProxyResult> => {
  const { httpMethod, path, body, queryStringParameters } = event;

  try {
    switch (`${httpMethod} ${path}`) {
      case 'GET /users':
        return await getUsers(queryStringParameters);
      case 'POST /users':
        return await createUser(JSON.parse(body || '{}'));
      case 'GET /users/{id}':
        const id = event.pathParameters?.id;
        return await getUser(id!);
      default:
        return response(404, { error: 'Nicht gefunden' });
    }
  } catch (error) {
    console.error('Lambda-Fehler:', error);
    return response(500, { error: 'Interner Serverfehler' });
  }
};

function response(statusCode: number, body: object): APIGatewayProxyResult {
  return {
    statusCode,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    },
    body: JSON.stringify(body),
  };
}

async function getUsers(params: any) {
  // Benutzerliste aus DynamoDB abrufen
  return response(200, { users: [] });
}

async function createUser(data: any) {
  return response(201, { id: 'new-user-id', ...data });
}

async function getUser(id: string) {
  return response(200, { id, name: 'User' });
}

Integration mit DynamoDB

> Erstelle ein CRUD-Utility für DynamoDB-Operationen.
// src/lib/dynamodb.ts
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import {
  DynamoDBDocumentClient,
  GetCommand,
  PutCommand,
  QueryCommand,
  DeleteCommand,
} from '@aws-sdk/lib-dynamodb';

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

const TABLE_NAME = process.env.TABLE_NAME!;

export async function getItem<T>(pk: string, sk: string): Promise<T | null> {
  const { Item } = await docClient.send(
    new GetCommand({
      TableName: TABLE_NAME,
      Key: { PK: pk, SK: sk },
    })
  );
  return (Item as T) || null;
}

export async function putItem(item: Record<string, any>): Promise<void> {
  await docClient.send(
    new PutCommand({
      TableName: TABLE_NAME,
      Item: {
        ...item,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      },
    })
  );
}

export async function queryItems<T>(
  pk: string,
  skPrefix?: string
): Promise<T[]> {
  const params: any = {
    TableName: TABLE_NAME,
    KeyConditionExpression: skPrefix
      ? 'PK = :pk AND begins_with(SK, :sk)'
      : 'PK = :pk',
    ExpressionAttributeValues: { ':pk': pk },
  };

  if (skPrefix) {
    params.ExpressionAttributeValues[':sk'] = skPrefix;
  }

  const { Items } = await docClient.send(new QueryCommand(params));
  return (Items as T[]) || [];
}

Infrastrukturdefinition mit AWS CDK

> Definiere einen Stack mit Lambda + API Gateway + DynamoDB in CDK.
// lib/api-stack.ts
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Construct } from 'constructs';

export class ApiStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // DynamoDB-Tabelle
    const table = new dynamodb.Table(this, 'MainTable', {
      partitionKey: { name: 'PK', type: dynamodb.AttributeType.STRING },
      sortKey: { name: 'SK', type: dynamodb.AttributeType.STRING },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
      removalPolicy: cdk.RemovalPolicy.RETAIN,
    });

    // Lambda-Funktion
    const apiHandler = new NodejsFunction(this, 'ApiHandler', {
      entry: 'src/handlers/api.ts',
      handler: 'handler',
      runtime: lambda.Runtime.NODEJS_20_X,
      architecture: lambda.Architecture.ARM_64,
      memorySize: 256,
      timeout: cdk.Duration.seconds(30),
      environment: {
        TABLE_NAME: table.tableName,
        NODE_OPTIONS: '--enable-source-maps',
      },
      bundling: {
        minify: true,
        sourceMap: true,
      },
    });

    table.grantReadWriteData(apiHandler);

    // API Gateway
    const api = new apigateway.RestApi(this, 'Api', {
      restApiName: 'My API',
      deployOptions: { stageName: 'v1' },
    });

    const users = api.root.addResource('users');
    users.addMethod('GET', new apigateway.LambdaIntegration(apiHandler));
    users.addMethod('POST', new apigateway.LambdaIntegration(apiHandler));
  }
}

Lokale Entwicklung und Tests

# Lokale Ausführung mit SAM
sam local start-api

# Bestimmte Funktion testen
sam local invoke ApiHandler -e events/get-users.json

# CDK-Deployment
cdk deploy --require-approval never

Zusammenfassung

Durch die Kombination von AWS Lambda und Claude Code können Sie vom Serverless-Architekturdesign bis zum IaC-Code effizient vorgehen. Siehe auch den AWS-Deployment-Leitfaden und den Serverless-Funktions-Leitfaden.

Details zu AWS Lambda finden Sie in der offiziellen AWS Lambda-Dokumentation.

#Claude Code #AWS Lambda #serverless #AWS #Cloud