mbklein

mbklein

Sanity Check: Right way to use Ecto/Postgres locks (and how to test them)

We’ve got a kind of producer/consumer workflow happening, involving three processes.

The main process inserts a whole bunch of records into the progress table in a single atomic bulk insert. (This ensures that our entire roster of work gets set up at once without interruption.) Each progress row has a status of pending.

The Creator process is a GenServer that (basically) does the following on an interval:

def create_stuff(opts) do
  # Grab `batch_size` waiting entries
  batch = from(p in Progress, where: p.status == "pending", limit: opts[:batch_size], lock: "FOR UPDATE NOWAIT") |> Repo.all()
  # Set their status to "processing"
  batch |> Repo.update_all(set: [status: "processing", updated_at: now])
  # Process them and mark them completed all in a transaction
  batch
  |> Enum.each(fn entry -> 
    Repo.transaction(fn ->
      Logger.info("Creating #{entry.name}")
      do_something_with(entry)
      Progress.changeset(entry, %{status: "complete"}
    end)
  end)
end

The Redriver process is a GenServer that sweeps the progress table and resets any entry that’s been processing longer than @timeout seconds (and is therefore assumed to be part of a stuck batch).

timeout = DateTime.utc_now() |> DateTime.add(-@timeout, :second)
from(p in Progress, where: p.status == "processing" and p.updated_at <= ^timeout)
|> Repo.update_all(set: [status: "pending", updated_at: DateTime.utc_now()])

The idea is that no two Creator processes should ever select the same set of progress rows to work on, but of course there’s that tiny window between batch = and update_all where another process could grab the same rows. Hence the lock.

This seems to be working in practice, in that we’ve observed that work gets duplicated without the lock and doesn’t seem to with the lock. But we’ve had trouble devising a test for it.

The latest attempt is:

test "concurrency" do
  Sandbox.mode(Repo, {:shared, self()})
  
  1..5 
  |> Enum.each(fn index ->
    Progress.changeset(%Progress{}, %{name: "TEST_ENTRY_#{index}"}) |> Repo.insert()
  )

  log =
    capture_log(fn ->
      Enum.each(1..5, fn _ ->
        spawn(fn -> Creator.create_stuff(batch_size: 2) end)
      end)

  :timer.sleep(1000)

  assert from(p in Progress, where: p.status == "complete") |> Repo.aggregate(:count) == 5
  assert assert Regex.scan(~r/Creating TEST_ENTRY_1/, log) |> length() == 1
end

The above test fails, because "Creating TEST_ENTRY_1" appears in the log 5 times – once for each spawned call to Creator.create_stuff/1.

Now that I’ve got all of that out of the way, here are my questions:

  1. Is this the right way to use FOR UPDATE NOWAIT locking?
  2. Is is possible that it’s working in reality but the Ecto Sandbox is getting in the way testing it properly?
  3. Is there a better way to accomplish what we’re trying to do here?

Most Liked

mbuhot

mbuhot

I would expect FOR UPDATE SKIP LOCKED here.

The docs say:

With NOWAIT , the statement reports an error, rather than waiting, if a selected row cannot be locked immediately. With SKIP LOCKED , any selected rows that cannot be immediately locked are skipped.

Yes, I think sandbox is sharing a single transaction among all the spawned processes, instead of allowing separate connections/transactions for each one.

Where Next?

Popular in Questions Top

openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New

We're in Beta

About us Mission Statement