# Keeping the last success in an Ecto upsert

Kogen Studio's watchdog runs on a timer. It opens incidents for things like stalled releases and watchers that stopped checking in. Finding a stalled release means the watchdog did its job. A failed tick means the watchdog itself couldn't complete its checks in at least one workspace.

We keep one status row for the watchdog. Every tick tries to insert the same ID, and Ecto's `on_conflict` tells Postgres what to do when that ID already exists. On failure, we use an update query because the next failure count depends on what's already in the row.

```elixir
failure = from t in "supervisor_ticks",
  update: [
    set: [last_tick_at: ^at, ok: false, workspaces: ^checked, error: ^error],
    inc: [consecutive_failures: 1]
  ]

row = %{id: 1, last_tick_at: at, ok: false, workspaces: checked,
        error: error, consecutive_failures: 1}

Repo.insert_all("supervisor_ticks", [row],
  conflict_target: [:id], on_conflict: failure)
```

On the first insert, the counter starts at 1 and `last_success_at` is empty. On conflict, `set` records the latest attempt and `inc` adds 1 to the stored counter. The update leaves `last_success_at` alone.

So if the checks finish at 10:00 and fail at 10:01 and 10:02, you can see the watchdog last ran at 10:02, last succeeded at 10:00, and has failed twice in a row. The next successful tick updates both timestamps and resets the counter.

https://hexdocs.pm/ecto/Ecto.Repo.html#c:insert_all/3

---

Created by: almirsarajcic
Date: November 30, 2026
URL: https://elixirdrops.net/d/hg2TtWsf
