Архитектурные шаблоны бессерверных систем
Изучите и применяйте распространённые архитектурные шаблоны бессерверных систем, такие как fan-out, scatter-gather и источники событий, для эффективного решения сложных бизнес-задач.
«Архитектурные шаблоны бессерверных систем» — бесплатный урок Serverless AWS Lambda Development на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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:
- Update inventory.
- Send a confirmation email.
- Generate a shipping label.
- 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) и разблокировать остальной курс Serverless AWS Lambda Development, подпишись на CoddyKit PRO. Курс Serverless AWS Lambda Development содержит 4 уроков всего.
Чему я научусь в уроке «Архитектурные шаблоны бессерверных систем»?
Изучите и применяйте распространённые архитектурные шаблоны бессерверных систем, такие как fan-out, scatter-gather и источники событий, для эффективного решения сложных бизнес-задач. Ты практикуешь Serverless AWS Lambda Development с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Serverless AWS Lambda Development?
Предыдущий опыт не требуется. Serverless AWS Lambda Development на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Архитектурные шаблоны бессерверных систем»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Serverless AWS Lambda Development?
Да. Каждый урок Serverless AWS Lambda Development включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Канареечные и сине-зелёные развёртывания
- Создание отказоустойчивых бессерверных систем
- Архитектурные шаблоны бессерверных систем
- Оптимизация затрат в бессерверных архитектурах