Skip to content

perf: batch cache (and some misc) optimizations#120

Draft
v0idpwn wants to merge 10 commits intomasterfrom
perf/optimize-batch-cache
Draft

perf: batch cache (and some misc) optimizations#120
v0idpwn wants to merge 10 commits intomasterfrom
perf/optimize-batch-cache

Conversation

@v0idpwn
Copy link
Copy Markdown

@v0idpwn v0idpwn commented Apr 6, 2026

Currently, BatchCache.put/2 always reads all pending messages and sorts them to detect overflow and discard the oldest messages. Since pending and in-flight messages are in the same table, it must filter to select only the pending ones.

This PR avoids the ets:select on every iteration by splitting pending and in-flight into two different tables. This allows us to use the size of the pending mesages ETS instead of selecting messages every time. I've considered a few different approaches (like using counters) but I felt like this was more straightforward.

When the batch is overflowing, it still runs the select and sort. So in case of a Logflare outage, #115 still sort of applies. But this should improve the performance when logflare is operational. In my tests, with a batch size of 100, the performance more than doubled, and memory was also decreased. I have added some stats in the commits. Notice that after I introduced the BatchServer, memory measurements must be done differently.

Some notes:

  • I also implemented a BatchServer. It avoids concurrent flushes (which were a problem on LogflareLogger), and facilitated thinking about concurrency. It also ensures that LogflareLogger also has periodic flushes (which it didn't, only the backend had).
  • Previously, flush was always sync. I made it async by default but sync if the pending list is at least a few batches big. Making it async by default allows it to handle more messages, but having a fallback to sync ensures it doesn't lose the backpressure that existed at this level.
  • I also have a few commits for some small random optimizations. They don't necessarily make a significative difference, but they make us have less reductions/allocations and were trivial enough.

v0idpwn added 9 commits April 5, 2026 11:56
Instead of filtering a single table by `api_request_started_at` on every
`put/2`, use two separate Etso tables: PendingLoggerEvent for events
waiting to be sent, and InFlightLoggerEvent for events currently being
posted to the API. This avoids scanning and sorting all pending entries
on each insert. The pending count is now retrieved via `:ets.info/2`
which is O(1).

Benchmark (1000x HttpBackend.handle_event/2):

              Before       After       Change
  ips         19.01        29.38       +55%
  average     52.62 ms     34.04 ms    -35%
  memory      79.01 MB     25.97 MB    -67%
  reductions  4.74 M       2.21 M      -53%
Use insert_all for pending-to-in-flight moves (one ETS call vs N) and
delete_all for clear (O(1) via ets:delete_all_objects). Pre-generate
in-flight IDs to avoid re-reading the table after insert.

To safely use these bulk operations, introduce a BatchServer GenServer
that serializes flush/clear/reset. put/2 still writes directly to ETS.
This also fixes a correctness issue where LogflareLogger.log/3 could
trigger concurrent flushes from arbitrary processes.

Benchmark (1000x HttpBackend.handle_event/2):

              Before       After        Change
  ips         29.38        41.26        +40%
  average     34.04 ms     24.24 ms     -29%
  memory      25.97 MB     18.23 MB     -30%
  reductions  2.21 M       1.44 M       -35%
Combine the read and reset into a single GenServer call so in-flight
events are moved back to pending atomically instead of two separate
round-trips.
In-flight events were only recovered for the HTTP backend. By handling
recovery at the BatchServer level it works for LogflareLogger too.
Avoids intermediate list allocation by combining the map and collect
steps into a single Map.new/2 call.
The result is discarded (only used for encodability check), so skip
the unnecessary IO.iodata_to_binary step.
Build ISO8601 binary directly from erlang datetime tuple components
instead of going through NaiveDateTime.from_erl!/to_iso8601.
Comment thread lib/logflare_logger/batch_server.ex Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant