# Serverless Architecture

Serverless architecture is a cloud computing execution model where the cloud provider (AWS, Azure, Google Cloud) dynamically manages the allocation and provisioning of servers. A serverless application runs in stateless compute containers that are event-triggered, ephemeral (may last for one invocation), and fully managed by the cloud provider.

## 1. "Serverless" is a Misnomer

Despite the name, servers still exist. The term "serverless" means that the developer does not have to worry about server management (patching, scaling, capacity planning).

*   **Traditional:** You rent a server (EC2), install OS, install Node.js, run your app. You pay for the server 24/7.
*   **Serverless:** You upload your code (function). The cloud provider runs it only when triggered. You pay only for the milliseconds it runs.

## 2. Key Components

### FaaS (Function as a Service)
This is the compute part. You deploy individual functions that perform a specific task.
*   **Examples:** AWS Lambda, Azure Functions, Google Cloud Functions.
*   **Characteristics:** Stateless, short-lived, event-driven.

### BaaS (Backend as a Service)
Third-party services that replace server-side functionality.
*   **Examples:** Firebase (Auth/DB), AWS Cognito (Auth), DynamoDB (Database).

## 3. How it Works

1.  **Event Trigger:** An event occurs (HTTP request, file upload to S3, database change).
2.  **Cold Start:** The provider spins up a container with your code (if one isn't already running).
3.  **Execution:** The function runs, processes the event, and returns a result.
4.  **Scale Down:** After a period of inactivity, the container is destroyed.

## 4. Pros and Cons

| Pros | Cons |
| :--- | :--- |
| **Cost:** Pay-per-use. Zero cost when idle. | **Cold Starts:** Latency spike when a function runs for the first time. |
| **Scalability:** Scales from 0 to 10,000 requests instantly. | **Vendor Lock-in:** Code is often tied to specific provider APIs. |
| **Ops-Free:** No OS updates or security patching. | **Debugging:** Harder to debug distributed, ephemeral functions. |

## 5. Use Cases

*   **REST APIs:** Using API Gateway + Lambda.
*   **File Processing:** Resizing an image immediately after it's uploaded to storage.
*   **Scheduled Tasks:** Running a cleanup script every night (Cron jobs).
*   **Chatbots:** Responding to webhook events.

## 6. Mitigating Cold Starts

A "Cold Start" happens when a function is invoked after being idle, requiring the provider to spin up a new container. This adds latency (100ms to several seconds).

*   **Keep it Warm:** Use "Provisioned Concurrency" (AWS) or a scheduled "ping" to keep containers alive.
*   **Language Choice:** Interpreted languages (Node.js, Python) generally start faster than compiled runtimes (Java, .NET) which require JVM initialization.
*   **Reduce Package Size:** Remove unused dependencies. Smaller code bundles download and unzip faster.
*   **Lazy Loading:** Don't load heavy libraries or database connections outside the handler unless necessary.

## 7. Function Composition

Since serverless functions are small and single-purpose, complex workflows require chaining them together.

*   **Chaining:** Function A calls Function B. (Not recommended due to double billing: you pay for A waiting for B).
*   **Orchestration (Step Functions):** Using a state machine service (like AWS Step Functions or Azure Logic Apps) to coordinate the execution of multiple functions. This handles retries, error handling, and parallel execution without code.

## 8. Serverless Security

Security in serverless environments requires a shift in mindset. While the cloud provider manages the OS and physical security, you are still responsible for application security.

*   **Least Privilege:** Assign granular IAM (Identity and Access Management) roles to each function. A function that only reads from S3 should not have permission to write to DynamoDB.
*   **Input Validation:** Since functions are often triggered by various event sources (API Gateway, S3, SNS), validate all incoming data to prevent injection attacks.
*   **Dependency Management:** Functions often rely on third-party libraries. Regularly scan dependencies for vulnerabilities (e.g., using `npm audit` or OWASP Dependency Check).
*   **Secrets Management:** Never hardcode API keys or database passwords in your function code. Use environment variables or a secrets manager (e.g., AWS Secrets Manager, Azure Key Vault).

[[programming/cloud-computing-basics]]
[[programming/microservices-architecture]]
[[programming/event-driven-architecture]]
[[programming/cybersecurity-basics]]