0Pricing
Serverless AWS Lambda Development · 강의

서버리스 아키텍처 패턴

팬아웃, 분산 수집, 이벤트 소싱과 같은 일반적인 서버리스 아키텍처 패턴을 살펴보고 적용하여 복잡한 비즈니스 문제를 효율적으로 해결합니다.

서버리스 아키텍처 패턴은(는) CoddyKit의 무료 Serverless AWS Lambda Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Serverless AWS Lambda Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Serverless AWS Lambda Development 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What are Serverless Patterns?

In serverless development, we often encounter similar challenges. Architectural patterns are proven, reusable solutions to these common problems.

They help us design scalable, resilient, and maintainable serverless applications by providing a blueprint for interaction between different services.

The Fan-Out Pattern

The Fan-Out pattern is when a single input event triggers multiple parallel processes or actions. Think of it like a ripple effect from one stone thrown into water.

This pattern is excellent for decoupling services and performing concurrent tasks. For example, a new file upload might need to be processed in several different ways at once.

Fan-Out: Image Processing Example

Imagine uploading an image. A Lambda function could 'fan out' this event, triggering separate processes for creating a thumbnail, adding a watermark, and extracting metadata—all in parallel.

Here's a conceptual Python example simulating this fan-out logic:

def process_image_event(image_id):
    print(f"Processing image: {image_id}")
    # Simulate publishing to different services
    print(f"  - Publishing to Thumbnail Service for {image_id}")
    print(f"  - Publishing to Watermark Service for {image_id}")
    print(f"  - Publishing to Metadata Service for {image_id}")

def main():
    print("--- Fan-Out Simulation ---")
    image_id = "img-12345.jpg"
    process_image_event(image_id)
    print("--- Simulation Complete ---")

if __name__ == "__main__":
    main()

The Scatter-Gather Pattern

The Scatter-Gather pattern involves sending a request to multiple recipients (scatter), collecting all their responses, and then aggregating them into a single response (gather).

This is often used for operations like searching across multiple data sources or comparing prices from different vendors.

Scatter-Gather: Product Search Example

When you search for a product, a Lambda could 'scatter' the query to various vendor APIs, then 'gather' and combine their results to show you the best options.

This example simulates querying different vendors and finding the cheapest product:

def get_product_info(vendor_name, product_id):
    # Simulate calling a vendor API
    print(f"  - Querying {vendor_name} for product {product_id}...")
    if vendor_name == "VendorA":
        return {"vendor": "VendorA", "price": 100, "stock": 5}
    elif vendor_name == "VendorB":
        return {"vendor": "VendorB", "price": 95, "stock": 10}
    elif vendor_name == "VendorC":
        return {"vendor": "VendorC", "price": 110, "stock": 3}
    return None

def main():
    print("--- Scatter-Gather Simulation ---")
    product_id = "PROD-XYZ"
    vendors = ["VendorA", "VendorB", "VendorC"]
    
    all_results = []
    print(f"Searching for product {product_id} across vendors:")
    for vendor in vendors:
        result = get_product_info(vendor, product_id)
        if result:
            all_results.append(result)
    
    print("\n--- Aggregated Results ---")
    if all_results:
        for res in all_results:
            print(f"  Vendor: {res['vendor']}, Price: ${res['price']}, Stock: {res['stock']}")
        
        cheapest = min(all_results, key=lambda x: x['price'])
        print(f"\nCheapest option: {cheapest['vendor']} at ${cheapest['price']}")
    else:
        print("No results found.")
    print("--- Simulation Complete ---")

if __name__ == "__main__":
    main()

The Event Sourcing Pattern

Event Sourcing is an architectural pattern where all changes to application state are stored as a sequence of immutable events. Instead of just storing the current state, you store how you got to that state.

This provides a complete audit trail, allows rebuilding past states, and is foundational for complex event-driven systems.

Event Sourcing: Order Management Example

In an e-commerce system, instead of updating an Order record, you record events like OrderCreated, ItemAdded, OrderShipped. The current state is then derived from applying these events in order.

Here's a simulation of recording events for an order:

import datetime

def record_event(event_type, payload):
    timestamp = datetime.datetime.now().isoformat()
    event = {
        "eventId": f"evt-{datetime.datetime.now().timestamp()}",
        "eventType": event_type,
        "timestamp": timestamp,
        "payload": payload
    }
    # In a real system, this would write to a database stream (e.g., DynamoDB Streams, Kinesis)
    print(f"Recorded Event: {event['eventType']} at {event['timestamp']}")
    print(f"  Payload: {event['payload']}")
    return event

def main():
    print("--- Event Sourcing Simulation ---")
    
    # Simulate an order creation
    order_id = "ORD-001"
    record_event("OrderCreated", {"orderId": order_id, "customer": "Alice", "initialItems": []})
    
    # Simulate adding an item
    record_event("ItemAdded", {"orderId": order_id, "itemId": "SKU-A", "quantity": 1})
    
    # Simulate updating an item quantity
    record_event("ItemQuantityUpdated", {"orderId": order_id, "itemId": "SKU-A", "newQuantity": 2})
    
    # Simulate shipping the order
    record_event("OrderShipped", {"orderId": order_id, "shippingProvider": "UPS"})
    
    print("\n--- Event Stream Recorded ---")

if __name__ == "__main__":
    main()

Benefits of Serverless Patterns

These patterns offer significant advantages for serverless applications:

  • Scalability: Easily handle increased load by adding more parallel processes.
  • Decoupling: Services operate independently, reducing dependencies and improving resilience.
  • Resilience: Failures in one part of a fan-out or scatter-gather workflow don't necessarily stop the entire process.
  • Auditability (Event Sourcing): A complete history of changes is invaluable for debugging, compliance, and analytics.

Choosing the Right Pattern

Selecting the correct pattern depends on your specific problem:

  • Use Fan-Out when one event needs to trigger multiple independent, parallel actions.
  • Use Scatter-Gather when you need to query multiple sources and aggregate their responses.
  • Use Event Sourcing when you need a complete, immutable history of changes, or complex temporal queries.

Often, these patterns can be combined within a larger serverless architecture.

Pattern Challenge

A new e-commerce platform needs to process customer orders. When an order is placed, the system must:

  1. Update inventory.
  2. Send a confirmation email.
  3. Generate a shipping label.
  4. Process payment.

Which serverless architectural pattern is best suited for coordinating these independent tasks after an order is placed?

Patterns Recap

We've explored key serverless architectural patterns: Fan-Out for parallel processing from a single event, Scatter-Gather for aggregating responses from multiple sources, and Event Sourcing for maintaining an immutable history of state changes.

Understanding these patterns helps you design robust, scalable, and resilient serverless applications, choosing the right tool for each complex problem.

자주 묻는 질문

“서버리스 아키텍처 패턴” 강의는 무료인가요?

네 — “서버리스 아키텍처 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Serverless AWS Lambda Development 강의 전체를 잠금 해제할 수 있습니다. Serverless AWS Lambda Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“서버리스 아키텍처 패턴”에서 뭘 배우나요?

팬아웃, 분산 수집, 이벤트 소싱과 같은 일반적인 서버리스 아키텍처 패턴을 살펴보고 적용하여 복잡한 비즈니스 문제를 효율적으로 해결합니다. 브라우저에서 직접 실행하는 실습 코드로 Serverless AWS Lambda Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Serverless AWS Lambda Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Serverless AWS Lambda Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“서버리스 아키텍처 패턴” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Serverless AWS Lambda Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Serverless AWS Lambda Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 카나리 및 블루/그린 배포
  2. 복원력 있는 서버리스 시스템 구축
  3. 서버리스 아키텍처 패턴
  4. 서버리스 아키텍처의 비용 최적화
← Serverless AWS Lambda Development(으)로 돌아가기