A history microservice records which videos users have watched. When video-streaming emits a “Viewed” message, history receives it and writes a record to its own database. Viewing history could later support finding a previously watched video, resuming playback, or recommendations; the implementation here focuses on recording views. section 5.4 section 5.8.6
Start with an Express service stub, then add a message receiver and database write. Run it alongside video-streaming with Docker Compose. Live reload lets a change to history restart that service without restarting video-streaming; startup or code errors appear in the Compose output. section 5.5.1 section 5.5.5
Two communication approaches serve the same recording task:
- Direct HTTP: video-streaming POSTs a message to history by service name and gets an immediate response indicating success or failure. section 5.7
- Indirect messaging: video-streaming publishes to RabbitMQ, and history consumes from a queue when ready. Messages can wait in the queue if history cannot keep up. section 5.8.2
Listing 5.12 Consuming “Viewed” messages from a RabbitMQ queue
--snip-- async function main() { --snip-- const historyCollection = db.collection("history"); await messageChannel.assertQueue("viewed", {}) #1 await messageChannel.consume("viewed", async (msg) { #2 const parsedMsg = JSON.parse(msg.content.toString()); #3 await historyCollection.insertOne({ #4 videoPath: parsedMsg.videoPath }); messageChannel.ack(msg); #5 }); --snip-- } #1 Asserts the existence of the “Viewed” message queue for incoming messages #2 Receives messages from the viewed queue #3 Parses the JSON message to a JavaScript object #4 Records the view in the history database #5 If there was no error, acknowledges the message
The queue consumer asserts the viewed queue, parses each JSON payload, inserts its videoPath into the history collection, and acknowledges the message after the insert succeeds. section 5.8.6
Check that a view was recorded
Start the HTTP example with `cd chapter-5/example-2 && docker compose up --build`, then visit `http://localhost:4001/video`. Check the Compose output for the sent and received “Viewed” message. With a MongoDB viewer connected to `localhost:4000`, confirm that refreshing the video creates another record in the history database’s videos collection. section 5.7.5
With indirect messaging, video-streaming can broadcast a view event without naming history as its destination. History handles that event today; another service could respond later without changing video-streaming. section 10.7.5
