☁️ Cloud

Serverless

Serverless

Runs code without server management. Lambda, Cloud Functions. Usage-based billing.

📖 Detailed Explanation

Serverless is a cloud computing model that runs code without managing server infrastructure. Developers focus only on business logic, while the cloud provider handles server provisioning, scaling, patching, and so on. It does not mean "there are no servers"; it means "you don't have to worry about servers."

FaaS (Function as a Service) is the representative serverless service. Examples include AWS Lambda, Google Cloud Functions, and Azure Functions. Functions run in response to events such as HTTP requests, file uploads, and DB changes. You are billed based on execution time (in ms) and the number of requests, so there is almost no cost when there is no traffic.

The advantages of serverless are virtually unlimited automatic scaling, elimination of operational burden, and usage-based billing. Even during sudden traffic spikes, instances are automatically added, and no cost is incurred during idle time. It is very well suited to MVPs, event-driven processing, and periodic batch jobs.

The drawbacks are Cold Start latency, execution time limits (15 minutes for AWS Lambda), and difficulty maintaining state. Container initialization time occurs on the first request or on a request after a long idle period. Provisioned Concurrency can keep instances warm, but it incurs additional cost. It may be unsuitable for complex, long-running tasks.

💻 Code Example

// AWS Lambda 함수 (TypeScript)
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, PutCommand, GetCommand } from '@aws-sdk/lib-dynamodb';

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

// Lambda 핸들러 함수
export const handler = async (
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
  try {
    const { httpMethod, body, pathParameters } = event;

    if (httpMethod === 'POST') {
      // 사용자 생성
      const userData = JSON.parse(body || '{}');

      await docClient.send(new PutCommand({
        TableName: process.env.USERS_TABLE!,
        Item: {
          userId: crypto.randomUUID(),
          ...userData,
          createdAt: new Date().toISOString()
        }
      }));

      return {
        statusCode: 201,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: 'User created' })
      };
    }

    if (httpMethod === 'GET') {
      // 사용자 조회
      const { userId } = pathParameters || {};

      const result = await docClient.send(new GetCommand({
        TableName: process.env.USERS_TABLE!,
        Key: { userId }
      }));

      if (!result.Item) {
        return {
          statusCode: 404,
          body: JSON.stringify({ error: 'User not found' })
        };
      }

      return {
        statusCode: 200,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(result.Item)
      };
    }

    return {
      statusCode: 405,
      body: JSON.stringify({ error: 'Method not allowed' })
    };

  } catch (error) {
    console.error('Error:', error);
    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'Internal server error' })
    };
  }
};

// serverless.yml (Serverless Framework)
/*
service: user-api
provider:
  name: aws
  runtime: nodejs20.x
  region: ap-northeast-2
  environment:
    USERS_TABLE: ${self:service}-users-${sls:stage}
  iam:
    role:
      statements:
        - Effect: Allow
          Action:
            - dynamodb:PutItem
            - dynamodb:GetItem
          Resource: !GetAtt UsersTable.Arn

functions:
  users:
    handler: src/handlers/users.handler
    events:
      - httpApi:
          path: /users
          method: post
      - httpApi:
          path: /users/{userId}
          method: get
    # 콜드 스타트 방지 (추가 비용 발생)
    # provisionedConcurrency: 2

resources:
  Resources:
    UsersTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:provider.environment.USERS_TABLE}
        BillingMode: PAY_PER_REQUEST
        AttributeDefinitions:
          - AttributeName: userId
            AttributeType: S
        KeySchema:
          - AttributeName: userId
            KeyType: HASH
*/

🗣️ Examples of Practical Conversations

In startup technology decisions:

"If you start with Lambda early on, you can launch an MVP with almost no infrastructure cost. Even when traffic is hard to predict, automatic scaling means you can rest easy. Later, once the traffic pattern stabilizes, you can consider migrating to containers."

In a technical interview:

"How do you solve the Lambda cold start problem?" - "There are several ways. You can keep instances warm with Provisioned Concurrency, minimize bundle size, use lightweight runtimes like Node.js or Python, lazy-load the SDK, and so on. You can also do periodic warming with CloudWatch Events."

In cost optimization:

"Lambda costs are higher than expected." - "Analyze the execution time. When you increase the memory setting, CPU increases proportionally too, so execution time may actually decrease and lower the cost. Use AWS Lambda Power Tuning to find the optimal memory."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

🔗 Related Terms

Container Kubernetes Edge Computing API Gateway Event-Driven

📚 Learn More

📄 AWS Lambda Official Documentation 📄 Serverless Framework Guide 📄 Lambda Best Practices