Serverless Functions Grundlagen
Serverless Functions: Code ohne Server
Serverless führt Code aus, ohne Server zu verwalten. Lernen Sie die Grundlagen von Functions as a Service (FaaS).
Was ist Serverless?
Traditionell:
┌────────────────────────────┐
│ Server (24/7 laufend) │
│ - OS Updates │
│ - Skalierung │ ← Sie verwalten
│ - Monitoring │
│ - Kosten auch ohne Traffic │
└────────────────────────────┘
Serverless:
┌────────────────────────────┐
│ Cloud Provider │
│ - Automatische Skalierung │
│ - Pay per Execution │ ← Provider verwaltet
│ - Keine Server-Wartung │
└────────────────────────────┘
↑
Ihr Code (Function)
Anbieter
| Anbieter | Service | Sprachen |
|---|---|---|
| AWS | Lambda | Node, Python, Go, Java, ... |
| Vercel | Functions | Node, Go, Python, Ruby |
| Cloudflare | Workers | JavaScript/TypeScript |
| Netlify | Functions | Node, Go |
AWS Lambda
// handler.js
exports.handler = async (event, context) => {
const name = event.queryStringParameters?.name || 'World';
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: `Hello, ${name}!`,
timestamp: new Date().toISOString(),
}),
};
};
// Mit API Gateway:
// GET /hello?name=Max
// → {"message": "Hello, Max!", "timestamp": "..."}
# Deployment mit SAM
# template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
HelloFunction:
Type: AWS::Serverless::Function
Properties:
Handler: handler.handler
Runtime: nodejs20.x
Events:
HelloAPI:
Type: Api
Properties:
Path: /hello
Method: get
# Deploy
sam build
sam deploy --guided
Vercel Functions
// api/hello.ts (Next.js / Vercel)
import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { name = 'World' } = req.query;
res.status(200).json({ message: `Hello, ${name}!` });
}
// Automatisch deployed als /api/hello
// Mit Edge Runtime (schneller, global)
export const config = {
runtime: 'edge',
};
export default function handler(request: Request) {
const { searchParams } = new URL(request.url);
const name = searchParams.get('name') || 'World';
return new Response(
JSON.stringify({ message: `Hello, ${name}!` }),
{ headers: { 'Content-Type': 'application/json' } }
);
}
Cloudflare Workers
// worker.js
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const name = url.searchParams.get('name') || 'World';
return new Response(
JSON.stringify({ message: `Hello, ${name}!` }),
{
headers: { 'Content-Type': 'application/json' },
}
);
},
};
// wrangler.toml
name = "my-worker"
main = "worker.js"
compatibility_date = "2024-01-01"
# Deploy
wrangler deploy
Einsatzgebiete
# Gut für: ✅ APIs und Webhooks ✅ Scheduled Tasks (Cron) ✅ Image Processing ✅ Authentication ✅ Form Handling ✅ Slack/Discord Bots # Weniger gut für: ❌ Long-running Processes (Timeout!) ❌ WebSocket Connections ❌ Stateful Applications ❌ Hochfrequente Workloads (Cold Starts)
Cold Starts
# Problem: Erste Anfrage nach Inaktivität ist langsam Request → [Cold Start: ~100-500ms] → Function → Response # Mitigation: 1. Provisioned Concurrency (AWS) 2. Keep-Warm Pings 3. Edge Functions (Cloudflare Workers: <1ms) 4. Kleine Bundle-Größen
Best Practices
// ✅ Stateless - kein lokaler State
// Falsch:
let counter = 0;
export function handler() {
counter++; // Funktioniert nicht zuverlässig!
}
// Richtig:
export function handler() {
const count = await db.increment('counter');
return count;
}
// ✅ Connections außerhalb des Handlers
// Falsch:
export function handler() {
const db = new Database(); // Jedes Mal neu!
}
// Richtig:
const db = new Database(); // Wiederverwendet!
export function handler() {
return db.query('...');
}
// ✅ Environment Variables für Config
const apiKey = process.env.API_KEY;
Kosten
# AWS Lambda Free Tier: # - 1 Million Requests/Monat # - 400,000 GB-Sekunden # Beispiel: API mit 100k Requests/Monat # → Oft komplett kostenlos! # Bei hohem Traffic: # Vergleichen Sie mit traditionellem Hosting # Serverless kann teurer werden bei: # - Sehr vielen Requests # - Langen Ausführungszeiten
💡 Tipp:
Starten Sie mit Vercel oder Netlify für einfache Projekte. AWS Lambda für komplexere Setups mit mehr Kontrolle.