Andrew Coelho

February 19, 2016

RethinkDB for Realtime Apps

RethinkDB makes adding real-time functionality to your app almost trivial. With RethinkDB's changefeeds, changes to app data can be emitted using a library like Socket.io and live updated across all connected clients.

I've recently connected a React + Redux app to RethinkDB using Socket.io, and want to discuss how I approached it. First, I subscribe to the store to monitor any changes and then emit a Socket event from the client to the Socket server describing the change. When a user causes an action to be dispatched by Redux, the store is updated and the Socket event is emitted. The Socket server then updates the database accordingly. The RethinkDB changefeed then emits an event from the Socket server to all connected clients which dispatches a Redux action to update each user's state. This makes it so that our database is the single source of truth, and the local state of each connected user will always be in sync with it.

I've created a sample app demonstrating the basics of how I accomplished this which you can see at Github.

The app is a simple leaderboard that allows players (in this case, scientists), to be ranked by selecting and adding points to them. You'll notice the data is persisted in RethinkDB and all connected clients live update to reflect the changes made in the database.

leaderboard.gif

My first experience with real-time apps involved using Meteor, which made it easy to perform real-time updates to all clients. But Meteor wont always be the best choice for building your apps. If you're starting a new app from scratch or have the flexibility to make changes in your existing app, choosing RethinkDB as your database will make it almost as easy as Meteor to integrate real-time functionality in your app.