SlideShare a Scribd company logo
EVENT-DRIVEN SYSTEMS
BACKED BY MONGODB
bit.ly/2DUYXNF
ANDRII LITVINOV
Platform engineer at Synergy
Sports Technology
CHALLENGES
• Duplicate records matching
• Game statistics calculations
• Reports read model calculations
Orders Payments
M
e
s
s
a
g
e
b
r
o
k
e
r
Place
Order
Order
Order
Placed
Order
Placed
Payment
Accepted
Payment
Payment
Accepted
M
e
s
s
a
g
e
b
r
o
k
e
r
Orders
Crash
Order
Placed
✕
Order
Placed
?Payments
✓
Order
Place
Order
KEY TAKEAWAY:
PERSIST STATE AND
PUBLISH EVENT
ATOMICALLY
EVENT SOURCING
Service 1
Event 1
Event 1
Event 1
Event 1
Event
Service 2
Event 1
Event 1
Event 1
Event 1
Event
APPLICATION EVENTS
Service
M
e
s
s
a
g
e
b
r
o
k
e
r
Entity EventLocal
transaction
Event
Publisher
TRANSACTION LOG TAILING
Service
M
e
s
s
a
g
e
b
r
o
k
e
r
Event
Publisher
Transaction Log
Entity
DEMO
OUR CONSIDERATIONS
• Go with Oplog tailing
• Event sourcing requires major redesign
• MongoDB 3.6 Change Streams just released
• MongoDB 3.4
• No ACID transactions support so far
OPLOG TAILING
• More efforts to implement { w: "majority" }
• Proven, reliable, widely used in production
• Emit event from Primary { w: 1 }
Pros
Cons
• Private undocumented API
• Advised against by MongoDB
CHANGE STREAMS 3.6
• Single collection per connection
• Not yet widely used in production
• { w: "majority" } out of the box
• Stable, well-documented API
Pros
Cons
• No way to emit from Primary { w: 1}
• Recommended by MongoDB
Event-Driven Systems With MongoDB
Event-Driven Systems With MongoDB
TAKEAWAY:
FOR PRIMARY-SECONDARY-
ARBITER (PSA) REPLICA SET
USE OPLOG TAILING
CHANGE STREAMS 4.0
• { w: "majority" } out of the box
• Option to resume from a given Timestamp
• Subscribe to database or entire deployment
Pros
Cons
• Only supports { w: "majority" }, no { w: 1}
• Recommended by MongoDB
TAKEAWAY:
FOR MONGODB 4.0 REPLICA
SET WITH 3+ DATA-
BEARING NODES USE
CHANGE STREAMS
var @object = (BsonDocument) operation["o"];
switch ((string) operation["op"])
{
case "i":
{
EmitDomainEvents(@object);
break;
}
case "u":
{
if (@object.TryGetValue("$set", out var set))
EmitDomainEvents((BsonDocument) set);
else
EmitDomainEvents(@object);
break;
}
}
var handler = container.GetInstance<IEventHandler<OrderPlaced>>();
Lifestyle.Singleton.CreateRegistration(() =>
new EventHandlersConsumer("payments", database,
new Dictionary<string, Func<DomainEvent, Task>>
{
{
nameof(OrderPlaced),
@event => handler.Handle((OrderPlaced) @event)
}
}, logger), container));
await events
.Find(filter.And(
filter.In("event._t", handlers.Keys),
filter.Gt(envelope => envelope.Timestamp, checkpoint.Position)))
.Sort(Builders<EventEnvelope>.Sort.Ascending(envelope => envelope.Timestamp))
.ForEachAsync(async envelope =>
{
if (handlers.TryGetValue(envelope.Event.GetType().Name, out var handler))
{
if (!string.IsNullOrEmpty(envelope.CorrelationId))
TraceContext.Set(envelope.CorrelationId, envelope.EventId);
await handler.Invoke(envelope.Event);
}
await SaveCheckpoint(checkpoint, envelope.Timestamp);
}, cancellationToken);
public async Task Handle(OrderPlaced @event)
{
if (@event.Amount >= 200)
{
var delay = new Random().Next(3000, 30000);
await Task.Delay(delay);
}
var payment = new Payment(ObjectId.GenerateNewId(), @event.SourceId);
payment.Process(@event.Amount);
await payments.Create(payment);
}
public void Process(decimal amount)
{
Amount = amount;
if (Amount >= 300)
{
Status = PaymentStatus.Rejected;
RecordEvent(new PaymentRejected(Id, OrderId, Amount));
}
else
{
Status = PaymentStatus.Accepted;
RecordEvent(new PaymentAccepted(Id, OrderId, Amount));
}
}
var futureEvent = observable.FirstOfType<OrderFulfilled, OrderDiscarded>(orderId);
var command = await request.Body.ReadAs<PlaceOrder>();
await handler.Handle(command);
try
{
await futureEvent;
response.StatusCode = (int) HttpStatusCode.Created;
}
catch (TimeoutException)
{
response.StatusCode = (int) HttpStatusCode.Accepted;
}
var order = await orders.Find(o => o.Id == orderId).FirstAsync();
await response.Body.Write(order);
SUMMARY
• Use change streams with MongoDB 4.0
and 3+ data-bearing nodes
• Write state and publish event atomically
• Use oplog tailing prior MongoDB 4.0
or with 2 data-bearing nodes
RESOURCES
Replication
https://www.slideshare.net/Stripe_talks/mongo-db-oplog
https://www.compose.com/articles/the-mongodb-oplog-and-node-js/
https://stackoverflow.com/questions/17878835/what-does-the-h-in-oplog-rs-document-stand-for
https://stackoverflow.com/questions/26935419/what-do-the-oplog-fields-actually-mean
Event-Driven-Architecture
https://www.nginx.com/blog/event-driven-data-management-microservices/
https://microservices.io/
https://skillsmatter.com/skillscasts/12115-keynote-not-just-events-developing-asynchronous-microservices
Domain model
http://dddcommunity.org/library/vernon_2011/
THANK YOU! QUESTIONS?
https://twitter.com/andriilitvinov
https://github.com/andrii-litvinov
https://www.upwork.com/fl/andriilitvinov

More Related Content

PPTX
Wireless pres ba
PPT
Ken 20150306 心得分享
PDF
JavaScript client API for Google Apps Script API primer
PPTX
Google apps script database abstraction exposed version
PPTX
Android getting started
PPTX
Dbabstraction
RTF
final
PPTX
ASP.NET WEB API
Wireless pres ba
Ken 20150306 心得分享
JavaScript client API for Google Apps Script API primer
Google apps script database abstraction exposed version
Android getting started
Dbabstraction
final
ASP.NET WEB API

What's hot (20)

PPTX
MongoDB.local DC 2018: Scaling Realtime Apps with Change Streams
PDF
Liquid Stream Processing Across Web Browsers and Web Servers
TXT
Bulk copy
PDF
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
PDF
Creating your own project's Quality Dashboard
PDF
PDF
Re:Invent 2018 Database Announcements
PDF
ヘルスケアサービスを実現する最新技術
〜HealthKit・GCP+Go〜
DOC
Database c# connetion
PPTX
Share pointtechies linqtosp-andsbs
PDF
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheet
PPT
2006 - Basta!: Advanced server controls
PDF
XWiki: The best wiki for developers
PPSX
Azure Mobile Services .NET Backend
PPSX
Azure DocumentDB
PDF
ヘルスケアサービスを実現する最新技術 〜HealthKit・GCP + Goの活用〜
DOCX
Exchange 2010/2013 Exchange Management Shell Command
PPTX
ATG Advanced RQL
PPTX
MongoDB.local Sydney: How and When to Use Multi-Document Distributed Transact...
PPTX
Docker & Azure
MongoDB.local DC 2018: Scaling Realtime Apps with Change Streams
Liquid Stream Processing Across Web Browsers and Web Servers
Bulk copy
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Creating your own project's Quality Dashboard
Re:Invent 2018 Database Announcements
ヘルスケアサービスを実現する最新技術
〜HealthKit・GCP+Go〜
Database c# connetion
Share pointtechies linqtosp-andsbs
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheet
2006 - Basta!: Advanced server controls
XWiki: The best wiki for developers
Azure Mobile Services .NET Backend
Azure DocumentDB
ヘルスケアサービスを実現する最新技術 〜HealthKit・GCP + Goの活用〜
Exchange 2010/2013 Exchange Management Shell Command
ATG Advanced RQL
MongoDB.local Sydney: How and When to Use Multi-Document Distributed Transact...
Docker & Azure
Ad

Similar to Event-Driven Systems With MongoDB (20)

PPTX
MongoDB.local Austin 2018: Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch A...
PPTX
Grokking Engineering - Data Analytics Infrastructure at Viki - Huy Nguyen
PDF
[WSO2Con EU 2018] Patterns for Building Streaming Apps
PDF
WSO2 Product Release Webinar - WSO2 Complex Event Processor
PDF
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
PDF
Introducing the WSO2 Complex Event Processor
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
PDF
Working with data using Azure Functions.pdf
PPTX
Azure Stream Analytics : Analyse Data in Motion
PPTX
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
PDF
Rethinking Syncing at AltConf 2019
PDF
WSO2 Product Release Webinar - Introducing the WSO2 Complex Event Processor
PDF
[WSO2Con Asia 2018] Patterns for Building Streaming Apps
PDF
Event Sourcing - what could go wrong - Devoxx BE
PDF
Implementing and Visualizing Clickstream data with MongoDB
PDF
Siddhi - cloud-native stream processor
PDF
CHOReOS Web Services FISL Conference Brazil 2012
PDF
NSA for Enterprises Log Analysis Use Cases
PDF
Building a Sustainable Data Platform on AWS
PDF
GDC 2015 - Game Analytics with AWS Redshift, Kinesis, and the Mobile SDK
MongoDB.local Austin 2018: Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch A...
Grokking Engineering - Data Analytics Infrastructure at Viki - Huy Nguyen
[WSO2Con EU 2018] Patterns for Building Streaming Apps
WSO2 Product Release Webinar - WSO2 Complex Event Processor
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
Introducing the WSO2 Complex Event Processor
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
Working with data using Azure Functions.pdf
Azure Stream Analytics : Analyse Data in Motion
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
Rethinking Syncing at AltConf 2019
WSO2 Product Release Webinar - Introducing the WSO2 Complex Event Processor
[WSO2Con Asia 2018] Patterns for Building Streaming Apps
Event Sourcing - what could go wrong - Devoxx BE
Implementing and Visualizing Clickstream data with MongoDB
Siddhi - cloud-native stream processor
CHOReOS Web Services FISL Conference Brazil 2012
NSA for Enterprises Log Analysis Use Cases
Building a Sustainable Data Platform on AWS
GDC 2015 - Game Analytics with AWS Redshift, Kinesis, and the Mobile SDK
Ad

Recently uploaded (20)

DOCX
573137875-Attendance-Management-System-original
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPT
Mechanical Engineering MATERIALS Selection
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
web development for engineering and engineering
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Well-logging-methods_new................
573137875-Attendance-Management-System-original
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Mechanical Engineering MATERIALS Selection
UNIT-1 - COAL BASED THERMAL POWER PLANTS
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
web development for engineering and engineering
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Structs to JSON How Go Powers REST APIs.pdf
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Internet of Things (IOT) - A guide to understanding
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Foundation to blockchain - A guide to Blockchain Tech
Well-logging-methods_new................

Event-Driven Systems With MongoDB

Editor's Notes

  • #2: Talk intro: - Event-Driven systems and challenges - MongoDB replication internals - Reference implementation with MongoDB and C#
  • #3: Company creates analytics of sport events based on videos.
  • #5: Multiple components involved in business transaction State change notifications Reactive Can make decisions independently (in isolation)
  • #7: TPC Degraded performance No support by message brokers Write ahead logging Too complex for simple cases Options?
  • #8: Best option where applicable No Kafka
  • #9: What to do with No-SQL? Searching conferences/talking to people. Not right-away obvious.
  • #10: Work with most No-SQL No explicit event publishing in the app code Can be hard to revers-engineer the event
  • #14: Went with Change Streams for PoC
  • #15: Stale resume token issue on staging Failed to upgrade to MongoDB 3.6.2 on prod
  • #17: 3.4 to 3.6 upgrade issue