이벤트 기반 아키텍처
Workers와 Deno를 사용하여 실시간 데이터와 사용자 작업에 반응하는 이벤트 기반 시스템을 구축합니다.
이벤트 기반 아키텍처은(는) CoddyKit의 무료 Edge Computing with Cloudflare Workers & Deno 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Edge Computing with Cloudflare Workers & Deno 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What is Event-Driven Architecture?
Welcome! Today we'll explore Event-Driven Architecture (EDA). It's a design pattern where services communicate by producing and consuming events, rather than direct calls.
Think of it like a news channel: producers (reporters) publish news (events), and consumers (viewers) react to the news they're interested in.
- Event: A significant change in state, like 'user registered'.
- Producer: The system that generates and sends an event.
- Consumer: The system that listens for and reacts to an event.
Why Event-Driven at the Edge?
EDA shines brightly at the edge, offering significant benefits for performance and scalability:
- Decoupling: Services operate independently, reducing dependencies.
- Scalability: Individual components can scale up or down based on event load.
- Real-time Responsiveness: React to user actions or data changes instantly.
- Resilience: If one consumer fails, others can still process events.
This makes your edge applications more robust and flexible.
Cloudflare Workers as Event Reactors
Cloudflare Workers are perfect for event-driven systems because they are inherently reactive. They spring into action when triggered by an event!
Common events that trigger Workers include:
- Incoming HTTP requests (e.g., an API call)
- Messages from a queue (e.g., Cloudflare Queues)
- Scheduled cron jobs
- Other Cloudflare service bindings
They act as lightweight, distributed consumers.
Code: Worker Reacting to HTTP Event
Here's a basic Worker that processes an incoming HTTP request as an 'event'. It reads a custom header to identify the event type and logs it.
Try changing the X-Event-Type header when you test it!
export default {
async fetch(request, env, ctx) {
const eventType = request.headers.get('X-Event-Type') || 'unknown_event';
const eventData = await request.json().catch(() => ({}));
console.log(`Worker received event: ${eventType}`);
console.log(`Event data: ${JSON.stringify(eventData)}`);
// In a real app, you'd process eventData here
return new Response(`Event '${eventType}' processed!`, { status: 200 });
},
};Deno as an Event Originator
Just as Workers consume events, Deno applications can act as event producers. A Deno backend service or a CLI tool might generate events.
For instance, a Deno script could:
- Detect a file change and send an event.
- Process data and publish a 'data_processed' event.
- Handle a user action and send a 'user_activity' event to your edge Worker.
Code: Deno Sends Event to Worker
This Deno script acts as a producer, sending a 'user_registered' event to our Cloudflare Worker via an HTTP POST request. The Worker then acts as the consumer.
Remember to replace 'YOUR_WORKER_URL' with your deployed Worker's URL!
// main.ts
async function sendUserRegisteredEvent() {
const workerUrl = "https://your-worker-name.your-account.workers.dev"; // Replace this!
const response = await fetch(workerUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Event-Type": "user_registered"
},
body: JSON.stringify({ userId: "user_abc", timestamp: Date.now() })
});
if (response.ok) {
console.log("User registered event sent successfully!");
} else {
console.error("Failed to send event:", response.status, await response.text());
}
}
sendUserRegisteredEvent();Cloudflare Queues for Robust Events
For truly robust event-driven systems, especially at the edge, Cloudflare Queues are invaluable. They act as an event bus, providing a reliable buffer between producers and consumers.
- Asynchronous: Producers don't wait for consumers to finish.
- Guaranteed Delivery: Messages are durably stored until processed.
- Load Leveling: Handles bursts of events without overwhelming consumers.
- Decoupling: Producers and consumers don't need to know about each other directly.
Code: Worker Publishes to a Queue
Here, a Worker receives an HTTP request (an event) and then publishes a message to a Cloudflare Queue. This offloads heavy processing to a separate consumer.
To make this runnable, you'd need to bind a Queue in your wrangler.toml file (e.g., [[queues.producers]] binding = "MY_QUEUE" queue_name = "my-event-queue").
export default {
async fetch(request, env, ctx) {
const eventData = await request.json().catch(() => ({}));
const eventType = eventData.type || 'api_trigger_event';
// Publish event to a Cloudflare Queue
// 'env.MY_QUEUE' refers to the queue binding configured
await env.MY_QUEUE.send({
eventType: eventType,
payload: eventData
});
return new Response(`Event '${eventType}' queued successfully!`, { status: 202 });
},
};Code: Worker Consuming Queue Messages
This Worker is configured to consume messages directly from a Cloudflare Queue. It processes each message in a batch, extracting the event type and payload.
This Worker would have a queue handler instead of (or in addition to) a fetch handler. You'd configure this in your wrangler.toml (e.g., [[queues.consumers]] queue = "my-event-queue").
export default {
async queue(batch, env, ctx) {
for (const message of batch.messages) {
const { eventType, payload } = message.body;
console.log(`Processing event from queue: ${eventType}`);
console.log(`Payload: ${JSON.stringify(payload)}`);
// Implement your actual event processing logic here
// e.g., update a database, send a notification, call another API
}
},
};Quick Check: Event-Driven Concepts
Which of the following are key benefits of using an Event-Driven Architecture at the edge?
Recap: Event-Driven Edge Apps
Great job! You've learned about Event-Driven Architectures and how they supercharge applications at the edge.
- EDA uses events, producers, and consumers for decoupled communication.
- Cloudflare Workers are ideal for consuming and producing edge events.
- Deno applications can act as powerful event producers.
- Cloudflare Queues provide robust, asynchronous event delivery for resilience and scale.
This pattern is key for building highly responsive, scalable, and fault-tolerant edge applications. Keep exploring how events can transform your architecture!
자주 묻는 질문
“이벤트 기반 아키텍처” 강의는 무료인가요?
네 — “이벤트 기반 아키텍처” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Edge Computing with Cloudflare Workers & Deno 강의 전체를 잠금 해제할 수 있습니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.
“이벤트 기반 아키텍처”에서 뭘 배우나요?
Workers와 Deno를 사용하여 실시간 데이터와 사용자 작업에 반응하는 이벤트 기반 시스템을 구축합니다. 브라우저에서 직접 실행하는 실습 코드로 Edge Computing with Cloudflare Workers & Deno을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Edge Computing with Cloudflare Workers & Deno을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Edge Computing with Cloudflare Workers & Deno은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“이벤트 기반 아키텍처” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Edge Computing with Cloudflare Workers & Deno 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Edge Computing with Cloudflare Workers & Deno 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.