Search⌘ K

Verify Multiple Server Behavior

Explore how to implement inventory event replication using Phoenix PubSub and GenServer to keep multiple server nodes synchronized in a real-time sneaker store application. Understand challenges of replication, ensure consistent operations with database checks, and test your setup for simultaneous multi-page updates.

Add replication of Inventory events

Phoenix PubSub can be used for more than Channel messages. It lets any process subscribe to a particular event type at its core. We will use PubSub to power the replication events for our Inventory. We’ll need to spin up a new GenServer to handle the events, as well as a context to dispatch the events.

Replication is not without its own challenges—nodes can become out of sync from this replicated approach. For non-critical data, scalability benefits are often worth the trade-off of potential data incorrectness. In Sneakers23, we never use the replicated data as a source of truth for essential operations, such as the purchase process. Instead, we use the database to ensure that these operations are consistent.

We’ll first write the GenServer and then work our way up through the various layers.

Elixir
# sneakers_23/lib/sneakers_23/replication/server.ex
defmodule Sneakers23.Replication.Server do
use GenServer
alias Sneakers23.Inventory
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
def init(_opts) do
Phoenix.PubSub.subscribe(Sneakers23.PubSub, "inventory_replication")
{:ok, nil}
end
def handle_info({:mark_product_released!, product_id}, state) do
Inventory.mark_product_released!(product_id, being_replicated?: true)
{:noreply, state}
end
def handle_info({:item_sold!, id}, state) do
Inventory.item_sold!(id, being_replicated?: true)
{:noreply, state}
end
end

...