SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Event-Based API
Patterns and
Practices
James Higginbotham
Executive API Consultant | LaunchAny
• API Architecture, Strategy, and Execution
• Based in Colorado Springs
• Across multiple verticals:
• Commercial Insurance
• Healthcare
• Hospitality
• Finance and Banking
• Travel
• Airline
Brief Introduction
Photo by Ian Baldwin on Unsplash
API design is an
architectural concern
that combines business,
product design, and
software engineering
Today’s Popular API Styles and Protocols
Notification Problem: API Polling is Wasteful
App API
98.5% of polling API requests send back
data that hasn’t changed.
https://nordicapis.com/stop-polling-and-consider-using-rest-hooks/
Review:
Messaging Concepts
7
Three Types of Messages
Calculate the
30-day sales
average
Component A
<Message Producer>
Component B
<Message Receiver>
Command Message:
30-day sales
average report
scheduled
Component A
<Message Receiver>
Component B
<Message Producer>
Reply Message:
30-day sales
average
updated
Component A
<Message Producer>
Component B
<Message Receiver>
Event Message:
8
Messages in Practice: Web APIs
GET /books
Accept: application/json
…
<empty>
Command Message
Protocol
Semantics
Request
Body
HTTP Request
200 OK
Content-Type:
application/json
…
{
"books": [
"title":"My book title",
…
]
}
Reply Message
Protocol
Semantics
Response
Body
HTTP Response
• Ask what kinds of questions the event needs to answer:
• What happened?
• Who did it happen to?
• Why did it occur?
• Example #1:
• Example #2:
Event Messages
_____
Traditional Message Brokers: Queues and Topics
Point-to-Point Messaging
via Queues
Fanout (Pub/Sub)
via Topics
Component
Message
Broker
Component
Publisher
Message
Broker
Subscriber
Subscriber
Subscriber
Component
Message B
Message A
Message A
Message B
Message A
Message A
Message A
Message A
Event-Driven Architecture (EDA) has
leveraged these patterns for decades.
Distributed Logs - Apache Kafka and Apache Pulsar
Topic A
Record
1
Record
2
Record
3
Record
4
Record
5
Record
6
Record
7
Record
8
Record
9
Record
10
Consumer B
Consumer A
Distributed Logs combine Fanout with historical record often
not available in traditional message brokers
Let’s learn how we can apply the same patterns to APIs
12
Photo by Thought Catalog on Unsplash
Async API Styles
Uni-Directional and Bi-Directional Webhooks
Webhook
Dispatcher Workflow
Engine
Messaging
App
Webhook
Receiver
Webhook
Receiver
Webhook
Dispatcher
HTTP POST /hooks/messages
HTTP POST /hooks/workflow
{
“lastState”: “review”,
“newState”: “approved”,
“workflowId” : …
}
{
“message”: “Can you please review?”,
“link”: “/articles/12345”,
“workflowId” : …
}
Ash: “Can you please review?”
Julie: Approved
1 2
1
2
Server-Sent Events
Source: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
App API
… time elapses …
Websocket
API Consumer
Web/Mobile/Server
HTTP/1.1 101 WebSocket Protocol Handshake
Date: Thu, 10 Sept 2020 14:53:18 GMT
Connection: Upgrade
Upgrade: WebSocket
…
GET ws://echo.websocket.org/?encoding=text
Origin: http://websocket.org
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
…
Hello, client
REST API Server
with WebSocket
support
<<WebSocket Enabled>>
Hello, server.
GraphQL Subscriptions
Source: https://graphql.github.io/graphql-spec/June2018/#sec-Subscription
gRPC Client and Server Streaming
gRPC Client gRPC Server
service Main {
rpc GetLatestOrders(stream OrderQuery)
returns (OrderResults) {}
}
gRPC Async Option 1: Client Streams to
Server
gRPC Client gRPC Server
gRPC Option 2: Server Streams to Client
service Main {
rpc GetLatestOrders(OrderQuery)
returns (stream Order) {}
}
gRPC Client gRPC Server
gRPC Async Option 3: Bi-Directional streaming
service Main {
rpc GetLatestOrders(stream OrderQuery)
returns (stream Order) {}
}
Async API Design
Patterns
”…if you’re going to start emitting events from a
piece of software, put just as much care into
[event design] as you would as you do in
specifying an API. Because event formats are a
contract, too.”
– Tim Bray
https://www.tbray.org/ongoing/When/201x/2019/11/17/Bits-On-the-Wire
AsyncAPI.com: Definition and Discovery
Design Pattern #1:
Thin Event Notification
Thin Event Notification (aka “Thin Events”)
• Broadcast only the necessary details to notify that
an event occurred
• Forces subscribers to fetch additional details to
complete a task
Use when:
• The desire is to prevent subscribers processing
stale data. They are forced to fetch the latest data
due to frequent changes or potentially delayed
processing
Design Pattern #2:
Hypermedia-Driven
Events
Hypermedia-Driven Events
• Include hypermedia links in event
payloads
• Helps consumers find the right
API for details
Use when:
• You wish to bridge event
notifications with API integration
Design Pattern #3:
Event-Carried State
Transfer
Photo by Priscilla Du
Event-Carried State Transfer
• Broadcasts all known data at the time of the event
• Often contain the entire record, avoiding the need to
contact the source system to conduct further work
Use when:
• Subscribers want a snapshot of the data with the event
• Sharing data state changes through message streaming
(Apache Kafka, Apache Pulsar, etc.) to support replaying
message history.
• Using event sourcing /CQRS to capture state changes
over time
Design Pattern #4:
Structured Event
Payloads
Structured Event Payloads
• Groups properties as nested structures
• Avoids flat structures that require subscribers to
figure out how properties are grouped
• Helps drive evolvability as property names are
scoped to the parent property (e.g.
addressLine1)
Use when:
• Event payloads require complex data structures
• Event payloads have nested 1-to-many
relationships as part of an event payload
Design Pattern #5:
Evolutionary Event
Schema
Evolutionary Event Schema
• Only add new payload properties that have
default values or are not required
• Don’t delete existing properties unless they
offer a default value (even when missing in
future events)
• Don’t rename property names
Use when:
• When you need to make changes to your
event payload structure but don’t want to
break existing subscribers
Design Pattern #6:
Offline and Error
Recovery Support
Offline and Error Recovery Support
• Supplement event notification channels with
APIs that allow offline consumers to catch-
up
• Also allows consumers to identify and
troubleshoot failed deliveries
Use when:
• When offline support is necessary to keep
consumers in-sync
• Manual recovery may be needed during
development or for troubleshooting
35
Leverage Recovery Support in Async Styles
App API
Disconnected
• Another option is to support recovery in the
API itself
• Server-Sent Events has this built-in
• Your API may need to apply a similar
pattern
Use when:
• When offline support is necessary to keep
consumers in-sync
• Recovery after a network failure needs to
be automated
Design Pattern #7:
Separate Internal and
External Events
Separate Internal and External Events
• Design internal events for coordinating
implementation details
• Design external events for notification and
extensibility
Use when:
• Event-driven architecture is being used
internally, but external events are desired
• Prevent leaking implementation details or
special knowledge of how your internal
systems operate
{
"event": {
"type": "paymentProcessed",
"orderId" : "abc123",
...
}
}
{
"eventType": "authorized",
"transactionId" : "ffe36193abc",
"authorizationServer": "auth7.mycompany.com",
"merchantId" : ”m0043286410",
"transactionAmountInCents" : "20899",
"transactionCurrency" : "USD",
...
}
vs.
Design Pattern #8:
Stateful Session
Support
Stateful Session API Design w/ Server Push
• Use resource instances for the interaction
model with a long-running query or agent
process
Use when:
• Interaction with a long-running operation,
LLM-backed service, or agent-based
service
• When the client submits a single message
and needs to look for messages as results
are returned
POST /chatSessions
{ ... }
201 Created
Location: /chatSessions/abc123
{
“chatSession": {
"type": ”query",
”sessionId" : "abc123",
”query" : ”What are the nearby airports to Austin, TX?",
“_links”: {
{
“rel”: “messages”,
“href”:”/chatSessions/abc123/messages”
}
}
...
}
GET /chatSessions/abc123/messages
Connection: keep-alive
Content-Type: text/event-stream
200 OK
Content-Type: text/event-stream
event: message
data: { … }
event: message
data: { … }
Bi-Directional + Stateful Session API Design
• Use resource instances for the interaction
model with a long-running query or agent
process
• Expands the interaction to support bi-
directional communication
Use when:
• When the client may submit one or more
messages and receive one or more
responses
• Useful for interacting with LLMs that require
training or session content
(e.g., ChatGPT-style)
POST /chatSessions
{ ... }
201 Created
Location: /chatSessions/abc123
{
“chatSession": {
”sessionId" : "abc123",
“_links”: {
{
“rel”: “messages”,
“href”:”/chatSessions/abc123/messages”
}
}
...
}
POST /chatSessions/abc123/messages
Connection: Upgrade
Upgrade: websocket
101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
{”query" : ”What are the nearby airports to Austin, TX?" }
{ … }
{ … }
{ … }
{”query" : ”What about near Fredericksburg, TX?" }
{ … }
Those comfortable with
EDA and Async APIs will
have an advantage when
delivering high value APIs
driven by LLMs and AI
James Higginbotham
james@launchany.com
@launchany
https://apideveloperweekly.com

Weitere ähnliche Inhalte

Ähnlich wie Event-Based API Patterns and Practices

Rohit_Kumar_Resume
Rohit_Kumar_ResumeRohit_Kumar_Resume
Rohit_Kumar_Resume
Rohit Kumar
 

Ähnlich wie Event-Based API Patterns and Practices (20)

From Kafka to BigQuery - Strata Singapore
From Kafka to BigQuery - Strata SingaporeFrom Kafka to BigQuery - Strata Singapore
From Kafka to BigQuery - Strata Singapore
 
Salesforce Winter 23 Release Webinar Slide Deck
Salesforce Winter 23 Release Webinar Slide DeckSalesforce Winter 23 Release Webinar Slide Deck
Salesforce Winter 23 Release Webinar Slide Deck
 
Benefits of Stream Processing and Apache Kafka Use Cases
Benefits of Stream Processing and Apache Kafka Use CasesBenefits of Stream Processing and Apache Kafka Use Cases
Benefits of Stream Processing and Apache Kafka Use Cases
 
성공적인 서비스로의 플랫폼 선택
성공적인 서비스로의 플랫폼 선택성공적인 서비스로의 플랫폼 선택
성공적인 서비스로의 플랫폼 선택
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless World
 
Kube con china_2019_7 missing factors for your production-quality 12-factor apps
Kube con china_2019_7 missing factors for your production-quality 12-factor appsKube con china_2019_7 missing factors for your production-quality 12-factor apps
Kube con china_2019_7 missing factors for your production-quality 12-factor apps
 
Design Microservice Architectures the Right Way
Design Microservice Architectures the Right WayDesign Microservice Architectures the Right Way
Design Microservice Architectures the Right Way
 
WSO2 MASTER CLASS ITALIA #11 - APIM 4.0 & approccio event based
WSO2 MASTER CLASS ITALIA #11 - APIM 4.0 & approccio event basedWSO2 MASTER CLASS ITALIA #11 - APIM 4.0 & approccio event based
WSO2 MASTER CLASS ITALIA #11 - APIM 4.0 & approccio event based
 
Rohit_Kumar_Resume
Rohit_Kumar_ResumeRohit_Kumar_Resume
Rohit_Kumar_Resume
 
Microservice 微服務
Microservice 微服務Microservice 微服務
Microservice 微服務
 
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
 
Realtime stream processing with kafka
Realtime stream processing with kafkaRealtime stream processing with kafka
Realtime stream processing with kafka
 
High Availability by Design
High Availability by DesignHigh Availability by Design
High Availability by Design
 
Modern Cloud-Native Streaming Platforms: Event Streaming Microservices with A...
Modern Cloud-Native Streaming Platforms: Event Streaming Microservices with A...Modern Cloud-Native Streaming Platforms: Event Streaming Microservices with A...
Modern Cloud-Native Streaming Platforms: Event Streaming Microservices with A...
 
A.S.Sivaprakash
A.S.SivaprakashA.S.Sivaprakash
A.S.Sivaprakash
 
ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2
 
Durable Streaming and Enterprise Messaging
Durable Streaming and Enterprise MessagingDurable Streaming and Enterprise Messaging
Durable Streaming and Enterprise Messaging
 
MSB Deep Dive
MSB Deep DiveMSB Deep Dive
MSB Deep Dive
 
Agile Data Integration: How is it possible?
Agile Data Integration: How is it possible?Agile Data Integration: How is it possible?
Agile Data Integration: How is it possible?
 
An introduction to Microsoft Graph for developers
An introduction to Microsoft Graph for developersAn introduction to Microsoft Graph for developers
An introduction to Microsoft Graph for developers
 

Mehr von LaunchAny

Mehr von LaunchAny (20)

Refining Your API Design - Architecture and Modeling Learning Event
Refining Your API Design - Architecture and Modeling Learning EventRefining Your API Design - Architecture and Modeling Learning Event
Refining Your API Design - Architecture and Modeling Learning Event
 
Event-based API Patterns and Practices - AsyncAPI Online Conference
Event-based API Patterns and Practices - AsyncAPI Online ConferenceEvent-based API Patterns and Practices - AsyncAPI Online Conference
Event-based API Patterns and Practices - AsyncAPI Online Conference
 
GlueCon 2019: Beyond REST - Moving to Event-Based APIs and Streaming
GlueCon 2019: Beyond REST - Moving to Event-Based APIs and StreamingGlueCon 2019: Beyond REST - Moving to Event-Based APIs and Streaming
GlueCon 2019: Beyond REST - Moving to Event-Based APIs and Streaming
 
Austin API Summit 2019 - APIs, Microservices, and Serverless: The Shape of Th...
Austin API Summit 2019 - APIs, Microservices, and Serverless: The Shape of Th...Austin API Summit 2019 - APIs, Microservices, and Serverless: The Shape of Th...
Austin API Summit 2019 - APIs, Microservices, and Serverless: The Shape of Th...
 
APIStrat Keynote: Lessons in Transforming the Enterprise to an API Platform
APIStrat Keynote: Lessons in Transforming the Enterprise to an API PlatformAPIStrat Keynote: Lessons in Transforming the Enterprise to an API Platform
APIStrat Keynote: Lessons in Transforming the Enterprise to an API Platform
 
Austin API Summit 2018: Are REST APIs Still Relevant Today?
Austin API Summit 2018: Are REST APIs Still Relevant Today?Austin API Summit 2018: Are REST APIs Still Relevant Today?
Austin API Summit 2018: Are REST APIs Still Relevant Today?
 
GlueCon 2018: Are REST APIs Still Relevant Today?
GlueCon 2018: Are REST APIs Still Relevant Today?GlueCon 2018: Are REST APIs Still Relevant Today?
GlueCon 2018: Are REST APIs Still Relevant Today?
 
Lessons in Transforming the Enterprise to an API Platform
Lessons in Transforming the Enterprise to an API PlatformLessons in Transforming the Enterprise to an API Platform
Lessons in Transforming the Enterprise to an API Platform
 
APIStrat 2017: API Design in the Age of Bots, IoT, and Voice
APIStrat 2017: API Design in the Age of Bots, IoT, and VoiceAPIStrat 2017: API Design in the Age of Bots, IoT, and Voice
APIStrat 2017: API Design in the Age of Bots, IoT, and Voice
 
API Design in the Age of Bots, IoT, and Voice
API Design in the Age of Bots, IoT, and VoiceAPI Design in the Age of Bots, IoT, and Voice
API Design in the Age of Bots, IoT, and Voice
 
APIStrat 2016: Moving Toward a Modular Enterprise
APIStrat 2016: Moving Toward a Modular EnterpriseAPIStrat 2016: Moving Toward a Modular Enterprise
APIStrat 2016: Moving Toward a Modular Enterprise
 
API:World 2016 - Applying Domain Driven Design to APIs and Microservices
API:World 2016 - Applying Domain Driven Design to APIs and MicroservicesAPI:World 2016 - Applying Domain Driven Design to APIs and Microservices
API:World 2016 - Applying Domain Driven Design to APIs and Microservices
 
Moving Toward a Modular Enterprise - All About the API Conference 2016
Moving Toward a Modular Enterprise - All About the API Conference 2016Moving Toward a Modular Enterprise - All About the API Conference 2016
Moving Toward a Modular Enterprise - All About the API Conference 2016
 
Designing APIs and Microservices Using Domain-Driven Design
Designing APIs and Microservices Using Domain-Driven DesignDesigning APIs and Microservices Using Domain-Driven Design
Designing APIs and Microservices Using Domain-Driven Design
 
Applying Domain-Driven Design to APIs and Microservices - Austin API Meetup
Applying Domain-Driven Design to APIs and Microservices  - Austin API MeetupApplying Domain-Driven Design to APIs and Microservices  - Austin API Meetup
Applying Domain-Driven Design to APIs and Microservices - Austin API Meetup
 
APIs Are Forever - How to Design Long-Lasting APIs
APIs Are Forever - How to Design Long-Lasting APIsAPIs Are Forever - How to Design Long-Lasting APIs
APIs Are Forever - How to Design Long-Lasting APIs
 
API Thinking - How to Design APIs Through Systems Design
API Thinking - How to Design APIs Through Systems DesignAPI Thinking - How to Design APIs Through Systems Design
API Thinking - How to Design APIs Through Systems Design
 
Swagger 2.0: Latest and Greatest
Swagger 2.0: Latest and GreatestSwagger 2.0: Latest and Greatest
Swagger 2.0: Latest and Greatest
 
Gluecon 2015 Recap
Gluecon 2015 RecapGluecon 2015 Recap
Gluecon 2015 Recap
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

Event-Based API Patterns and Practices

  • 1. Event-Based API Patterns and Practices James Higginbotham Executive API Consultant | LaunchAny
  • 2. • API Architecture, Strategy, and Execution • Based in Colorado Springs • Across multiple verticals: • Commercial Insurance • Healthcare • Hospitality • Finance and Banking • Travel • Airline Brief Introduction Photo by Ian Baldwin on Unsplash
  • 3. API design is an architectural concern that combines business, product design, and software engineering
  • 4. Today’s Popular API Styles and Protocols
  • 5. Notification Problem: API Polling is Wasteful App API 98.5% of polling API requests send back data that hasn’t changed. https://nordicapis.com/stop-polling-and-consider-using-rest-hooks/
  • 7. 7 Three Types of Messages Calculate the 30-day sales average Component A <Message Producer> Component B <Message Receiver> Command Message: 30-day sales average report scheduled Component A <Message Receiver> Component B <Message Producer> Reply Message: 30-day sales average updated Component A <Message Producer> Component B <Message Receiver> Event Message:
  • 8. 8 Messages in Practice: Web APIs GET /books Accept: application/json … <empty> Command Message Protocol Semantics Request Body HTTP Request 200 OK Content-Type: application/json … { "books": [ "title":"My book title", … ] } Reply Message Protocol Semantics Response Body HTTP Response
  • 9. • Ask what kinds of questions the event needs to answer: • What happened? • Who did it happen to? • Why did it occur? • Example #1: • Example #2: Event Messages _____
  • 10. Traditional Message Brokers: Queues and Topics Point-to-Point Messaging via Queues Fanout (Pub/Sub) via Topics Component Message Broker Component Publisher Message Broker Subscriber Subscriber Subscriber Component Message B Message A Message A Message B Message A Message A Message A Message A Event-Driven Architecture (EDA) has leveraged these patterns for decades.
  • 11. Distributed Logs - Apache Kafka and Apache Pulsar Topic A Record 1 Record 2 Record 3 Record 4 Record 5 Record 6 Record 7 Record 8 Record 9 Record 10 Consumer B Consumer A Distributed Logs combine Fanout with historical record often not available in traditional message brokers
  • 12. Let’s learn how we can apply the same patterns to APIs 12 Photo by Thought Catalog on Unsplash
  • 14. Uni-Directional and Bi-Directional Webhooks Webhook Dispatcher Workflow Engine Messaging App Webhook Receiver Webhook Receiver Webhook Dispatcher HTTP POST /hooks/messages HTTP POST /hooks/workflow { “lastState”: “review”, “newState”: “approved”, “workflowId” : … } { “message”: “Can you please review?”, “link”: “/articles/12345”, “workflowId” : … } Ash: “Can you please review?” Julie: Approved 1 2 1 2
  • 16. Websocket API Consumer Web/Mobile/Server HTTP/1.1 101 WebSocket Protocol Handshake Date: Thu, 10 Sept 2020 14:53:18 GMT Connection: Upgrade Upgrade: WebSocket … GET ws://echo.websocket.org/?encoding=text Origin: http://websocket.org Connection: Upgrade Upgrade: websocket Sec-WebSocket-Version: 13 … Hello, client REST API Server with WebSocket support <<WebSocket Enabled>> Hello, server.
  • 18. gRPC Client and Server Streaming gRPC Client gRPC Server service Main { rpc GetLatestOrders(stream OrderQuery) returns (OrderResults) {} } gRPC Async Option 1: Client Streams to Server gRPC Client gRPC Server gRPC Option 2: Server Streams to Client service Main { rpc GetLatestOrders(OrderQuery) returns (stream Order) {} } gRPC Client gRPC Server gRPC Async Option 3: Bi-Directional streaming service Main { rpc GetLatestOrders(stream OrderQuery) returns (stream Order) {} }
  • 20. ”…if you’re going to start emitting events from a piece of software, put just as much care into [event design] as you would as you do in specifying an API. Because event formats are a contract, too.” – Tim Bray https://www.tbray.org/ongoing/When/201x/2019/11/17/Bits-On-the-Wire
  • 22. Design Pattern #1: Thin Event Notification
  • 23. Thin Event Notification (aka “Thin Events”) • Broadcast only the necessary details to notify that an event occurred • Forces subscribers to fetch additional details to complete a task Use when: • The desire is to prevent subscribers processing stale data. They are forced to fetch the latest data due to frequent changes or potentially delayed processing
  • 25. Hypermedia-Driven Events • Include hypermedia links in event payloads • Helps consumers find the right API for details Use when: • You wish to bridge event notifications with API integration
  • 26. Design Pattern #3: Event-Carried State Transfer Photo by Priscilla Du
  • 27. Event-Carried State Transfer • Broadcasts all known data at the time of the event • Often contain the entire record, avoiding the need to contact the source system to conduct further work Use when: • Subscribers want a snapshot of the data with the event • Sharing data state changes through message streaming (Apache Kafka, Apache Pulsar, etc.) to support replaying message history. • Using event sourcing /CQRS to capture state changes over time
  • 29. Structured Event Payloads • Groups properties as nested structures • Avoids flat structures that require subscribers to figure out how properties are grouped • Helps drive evolvability as property names are scoped to the parent property (e.g. addressLine1) Use when: • Event payloads require complex data structures • Event payloads have nested 1-to-many relationships as part of an event payload
  • 31. Evolutionary Event Schema • Only add new payload properties that have default values or are not required • Don’t delete existing properties unless they offer a default value (even when missing in future events) • Don’t rename property names Use when: • When you need to make changes to your event payload structure but don’t want to break existing subscribers
  • 32. Design Pattern #6: Offline and Error Recovery Support
  • 33. Offline and Error Recovery Support • Supplement event notification channels with APIs that allow offline consumers to catch- up • Also allows consumers to identify and troubleshoot failed deliveries Use when: • When offline support is necessary to keep consumers in-sync • Manual recovery may be needed during development or for troubleshooting
  • 34. 35 Leverage Recovery Support in Async Styles App API Disconnected • Another option is to support recovery in the API itself • Server-Sent Events has this built-in • Your API may need to apply a similar pattern Use when: • When offline support is necessary to keep consumers in-sync • Recovery after a network failure needs to be automated
  • 35. Design Pattern #7: Separate Internal and External Events
  • 36. Separate Internal and External Events • Design internal events for coordinating implementation details • Design external events for notification and extensibility Use when: • Event-driven architecture is being used internally, but external events are desired • Prevent leaking implementation details or special knowledge of how your internal systems operate { "event": { "type": "paymentProcessed", "orderId" : "abc123", ... } } { "eventType": "authorized", "transactionId" : "ffe36193abc", "authorizationServer": "auth7.mycompany.com", "merchantId" : ”m0043286410", "transactionAmountInCents" : "20899", "transactionCurrency" : "USD", ... } vs.
  • 37. Design Pattern #8: Stateful Session Support
  • 38. Stateful Session API Design w/ Server Push • Use resource instances for the interaction model with a long-running query or agent process Use when: • Interaction with a long-running operation, LLM-backed service, or agent-based service • When the client submits a single message and needs to look for messages as results are returned POST /chatSessions { ... } 201 Created Location: /chatSessions/abc123 { “chatSession": { "type": ”query", ”sessionId" : "abc123", ”query" : ”What are the nearby airports to Austin, TX?", “_links”: { { “rel”: “messages”, “href”:”/chatSessions/abc123/messages” } } ... } GET /chatSessions/abc123/messages Connection: keep-alive Content-Type: text/event-stream 200 OK Content-Type: text/event-stream event: message data: { … } event: message data: { … }
  • 39. Bi-Directional + Stateful Session API Design • Use resource instances for the interaction model with a long-running query or agent process • Expands the interaction to support bi- directional communication Use when: • When the client may submit one or more messages and receive one or more responses • Useful for interacting with LLMs that require training or session content (e.g., ChatGPT-style) POST /chatSessions { ... } 201 Created Location: /chatSessions/abc123 { “chatSession": { ”sessionId" : "abc123", “_links”: { { “rel”: “messages”, “href”:”/chatSessions/abc123/messages” } } ... } POST /chatSessions/abc123/messages Connection: Upgrade Upgrade: websocket 101 Switching Protocols Upgrade: websocket Connection: Upgrade {”query" : ”What are the nearby airports to Austin, TX?" } { … } { … } { … } {”query" : ”What about near Fredericksburg, TX?" } { … }
  • 40. Those comfortable with EDA and Async APIs will have an advantage when delivering high value APIs driven by LLMs and AI

Hinweis der Redaktion

  1. Revisiting past messages vs. Receiving new pushed messages
  2. Incoming webhooks for third-party integration
  3. SSE mimics typical HTTP-based styles. SSE is mono-directional (server to client), HTTP protocol with error handling standards. It requires no sub-protocol and is flexible to support a variety of payload formats.
  4. WebSockets are bilateral (you don’t always need bi-direction), not HTTP (some proxy won’t let it go through) “protocol” without standards for error handling. WebSockets are great for real-time and long-lived bi-directional communications. Websockets support text and binary format and often choose a sub-protocol that defines how clients will communicate
  5. Tim Bray: AWS SQS/SNS, et. al