Architecture Patterns

Serverless and FaaS: Event-Driven Compute Without Managing Servers

Learn serverless architecture and Function-as-a-Service, including cold starts, stateless execution, event-driven workflows, operational limits, and when serverless is the right choice.

serverlessFaaSLambdacold startsevent-drivenarchitecture

Why Serverless?

Serverless is an execution model where the cloud provider manages the servers, runtime scaling, patching, capacity planning, and much of the operational plumbing. You still write code and own the architecture, but you do not provision long-running application servers for every workload.

Function-as-a-Service (FaaS) is the most common serverless compute model. You deploy small functions, and the platform runs them in response to events.

Key idea: Serverless does not mean "no servers." It means the server lifecycle is hidden behind a managed execution platform.


Traditional Compute vs Serverless

ConcernTraditional ServiceServerless Function
ScalingConfigure instances or autoscalingPlatform scales per event
BillingPay for provisioned capacityPay per request and duration
RuntimeLong-running processShort-lived invocation
StateCan keep local memory stateMust be stateless
OperationsPatch, deploy, size, monitor hostsMonitor functions and managed services

Function-as-a-Service

In FaaS, each function has a trigger, handler, runtime, configuration, and permissions.

Common Triggers

TriggerExample Use Case
HTTP requestAPI endpoint, webhook receiver
Queue messageBackground job processor
Object storage eventImage resize after upload
Database streamBuild search index, sync analytics
ScheduleNightly cleanup, report generation
Event busReact to business events

Handler Shape

ts
type OrderPlacedEvent = {
  orderId: string;
  customerId: string;
  totalAmount: number;
};

export async function handleOrderPlaced(event: OrderPlacedEvent) {
  await reserveInventory(event.orderId);
  await sendConfirmationEmail(event.customerId);

  return { status: "accepted" };
}

The handler should be small, idempotent, and explicit about dependencies. Heavy orchestration, long waits, and hidden shared state make functions difficult to reason about.


Statelessness

Serverless functions can be reused between invocations, but you must not depend on local process memory for correctness. The platform may start a new execution environment at any time.

What Can Live Inside the Function?

DataSafe?Notes
Database connection poolUsuallyReuse for performance, but reconnect on failure
In-memory cacheSometimesOptimization only, never source of truth
User sessionNoStore in Redis, database, or signed tokens
Idempotency keyNoStore externally with a uniqueness constraint
Config valuesYesLoad from environment or config service
⚠️

Do not rely on warm containers: A warm function can make repeated calls faster, but it is not a durability or coordination mechanism.


Cold Starts

A cold start happens when the platform must create a new execution environment before running your handler. The delay includes container setup, runtime startup, dependency loading, and initialization code.

Reducing Cold Start Impact

TechniqueHelps WithTrade-off
Keep dependencies smallRuntime initializationLess framework convenience
Initialize lazilyFirst request pathMore code discipline
Use provisioned concurrencyLatency-sensitive APIsHigher fixed cost
Choose lighter runtimesStartup timeRuntime ecosystem limits
Move work asyncUser-facing latencyEventual consistency

Cold starts matter most on synchronous user-facing paths. They matter less for background processing, scheduled jobs, and event consumers where a few hundred milliseconds do not affect user experience.


Event-Driven Serverless Workflows

Serverless works best when the system is naturally event-driven. A function receives an event, performs one bounded action, emits another event, and exits.

Orchestration vs Choreography

StyleHow It WorksBest For
OrchestrationA workflow engine coordinates each stepBusiness process with clear state machine
ChoreographyServices react to events independentlyLoosely coupled domain reactions

Use orchestration when the process needs explicit retries, compensation, human-visible status, or strict ordering. Use choreography when downstream reactions can evolve independently.


Limits and Constraints

Serverless platforms intentionally limit execution. Those limits are part of the architecture.

ConstraintDesign Implication
Max execution durationBreak long jobs into steps
Memory and CPU couplingTune memory to get enough CPU
Payload size limitsStore large payloads externally
Concurrency limitsProtect databases and downstream services
Temporary disk onlyUse object storage for durable files
Regional executionPlan latency and data residency
💡

Concurrency is a backpressure tool: Unlimited function scaling can overload a database. Set concurrency limits, use queues, and size connection pools deliberately.


Data Access Patterns

Direct Function to Database

Simple, but high concurrency can create too many database connections.

Queue Buffered Writes

Better for smoothing spikes and protecting downstream systems.

Managed Service First

Good for file processing, analytics pipelines, and asynchronous workflows.


Observability

Serverless systems are distributed systems. You need correlation IDs, structured logs, metrics, and traces from the start.

SignalWhat to Track
LogsFunction input metadata, decision points, error context
MetricsInvocations, errors, duration, throttles, concurrency
TracesCross-function and downstream service latency
Dead-letter queuesFailed events that need replay or manual inspection
CostRequests, duration, memory, provisioned concurrency

When to Use Serverless

WorkloadRecommendation
Spiky trafficStrong fit
Scheduled jobsStrong fit
Event processingStrong fit
WebhooksStrong fit
Long-running computeUsually avoid
Predictable high-throughput serviceCompare cost carefully
Low-latency trading or gaming pathUsually avoid
Heavy stateful protocolAvoid

Common Anti-Patterns

Anti-PatternProblemBetter Approach
One giant functionHard to test, deploy, and reason aboutSplit by business action
Function chains everywhereDebugging becomes painfulUse workflow engine or event bus
Direct database stormToo many connections during spikesQueue, pooler, or concurrency limits
Hidden local stateBreaks on cold start or rescheduleExternal durable state
No idempotencyRetries create duplicatesStore idempotency keys
Serverless for everythingCost and limits surprise youMatch compute model to workload

What to Remember for Interviews

  1. Serverless shifts operations: You manage architecture and code; the provider manages runtime capacity.
  2. Functions are stateless: Store durable state externally.
  3. Cold starts are workload-dependent: Critical for synchronous APIs, less critical for async jobs.
  4. Design for retries: At-least-once delivery means idempotency is mandatory.
  5. Protect downstream systems: Function scaling can overwhelm databases and third-party APIs.

Practice: Design a serverless image upload pipeline. Include upload, validation, thumbnail generation, virus scanning, metadata extraction, retries, and failure handling.