maxim

maxim

I wrote a library for building leaderboards. Would love any feedback. This is the list of features from the readme:

  • Ranks, percentiles, any custom stats of your choice
  • Concurrent reads, sequential writes
  • Stream API access to records from the top and the bottom
  • O(1) querying of any record by id
  • Auto-populating data on leaderboard startup
  • Adding, updating, removing, upserting of individual entries in live leaderboard
  • Fetching a range of records around a given id (contextual leaderboard)
  • Pluggable data stores: EtsStore for big boards, TermStore for dynamic mini boards
  • Atomic full repopulation in ~O(2n log n) time
  • Multi-node support
  • Extensibility for storage engines (CxLeaderboard.Storage behaviour)

github | docs | hex.pm

Showing Posts 1 to 10

idi527

idi527

:waving_hand:

For the term storage, :gb_trees might be a better fit than lists in maps.

I think DemonWare used them together with ets to keep rankings in call of duty. But that was before maps were introduced.

maxim

maxim OP

Wow that presentation is full of interesting insights, thank you! And gb_trees looks like a useful structure, will read more about it (esp. once erlang documentation site starts loading for me).

idi527

idi527

I wanted to link it but the website was down for me as well … You can do erl -man gb_trees in your shell.

amnu3387

amnu3387

I’ll probably give it a try soon

maxim

maxim OP

Let me know how it goes or if you need any help/have questions. Happy to help.

jonathanleang

jonathanleang

Can I get a example for Postgres auto-populate on startup.

I got the following but can’t get it to work. I think my issue is the connection is closed when the transaction ended.
related issue. Using Postgrex.stream with transactions · Issue #373 · elixir-ecto/postgrex · GitHub

worker(CxLeaderboard.Leaderboard, [:global, [data: loadDataToLeaderboard(pid)]])

def loadDataToLeaderboard(pid) do
{:ok, stream} = Postgrex.transaction(pid, fn(conn) →
Postgrex.stream(conn, “SELECT id, elo FROM users”, , max_rows: :infinity, timeout: :infinity)
end)
stream
end

maxim

maxim OP

@jonathanleang Interesting. I’ve never tried using these Ecto streams, I don’t think they play too well with a case where the stream should live for a long time. In our case I wrote my own module called StreamExt and implemented a couple of streaming functions in it. One based on offset/limit, and another (more efficient one) based on id comparisons.

defmodule StreamExt do
  @doc """
  Stream data in batches from an Ecto repo using a query.
  """
  def ecto_in_batches(repo, query, batch_size \\ 1000) do
    import Ecto.Query, only: [from: 1, from: 2]

    Stream.unfold(0, fn
      :done ->
        nil

      offset ->
        results =
          repo.all(from(_ in query, offset: ^offset, limit: ^batch_size))

        if length(results) < batch_size,
          do: {results, :done},
          else: {results, offset + batch_size}
    end)
  end

  def ecto_in_batches_by_id(repo, query, batch_size \\ 1000) do
    import Ecto.Query, only: [from: 2]

    Stream.unfold(-1, fn
      :done ->
        nil

      last_id ->
        results =
          repo.all(
            from(
              r in query,
              where: r.id > ^last_id,
              limit: ^batch_size
            )
          )

        {new_last_id, count} =
          results
          |> Enum.reduce({-1, 0}, fn r, {_, i} -> {elem(r, 0), i + 1} end)

        if count < batch_size,
          do: {results, :done},
          else: {results, new_last_id}
    end)
  end
end
maxim

maxim OP

Hey, just following up, did you manage to make it work?

jonathanleang

jonathanleang

@maxim
Thanks for following up, I have been trying for some time now, but kind of stuck.

here is what I got now.

   worker(CxLeaderboard.Leaderboard,[
    :global, 
    [data: loadDataToLeaderboard()]
  ])

 def loadDataToLeaderboard() do
     StreamExt.ecto_in_batches_by_id(Darkmoor.Repo, Darkmoor.User, 5)
     |> Stream.map(fn(batch) ->
       Enum.map(batch, fn({id, elo, name}) -> 
           {{elo, id}, name}
           end)
       end)
       # [{{100, 1}, "name1"}, {{200, 2}, "name2"}] this works
   end



  def ecto_in_batches_by_id(repo, query, batch_size \\ 1000) do
    import Ecto.Query, only: [from: 2]

    Stream.unfold(-1, fn
      :done ->
        nil

      last_id ->
        results =
          repo.all(
            from(
              r in query,
              select: {r.id, r.elo, r.name},
              where: r.id > ^last_id,
              limit: ^batch_size
            )
          )

        {new_last_id, count} =
          results
          |> Enum.reduce({-1, 0}, fn r, {_, i} -> {elem(r, 0), i + 1} end)
        if count < batch_size,
          do: {results, :done},
          else: {results, new_last_id}
    end)
  end
maxim

maxim OP

Ah I see, let me give you a specific solution here. I kind of forgot that my batch function wasn’t for direct usage. Try the following:

  1. Add this file to your elixir project: stream_ext.ex · GitHub

  2. Use this function:

    def leaderboard_stream() do
      import Ecto.Query, only: [from: 2]
      query = from(r in Darkmoor.User, select: {{r.elo, r.id}, r.name})
      StreamExt.ecto(Darkmoor.Repo, query, batch_size: 5, strategy: :id)
    end
    
  3. And finally declare your worker like this:

    worker(CxLeaderboard.Leaderboard, [:global, [data: leaderboard_stream()]])
    

Let me know if this works.

Where Next? Top

Trending in Announcing Top

woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
MRdotB
I needed to reuse React components from my Chrome extension in my Phoenix/LiveView backend. I noticed that for Svelte/Vue, there are live...
New
woylie
I released Doggo, a collection of unstyled Phoenix components. https://github.com/woylie/doggo Features Unstyled Phoenix components....
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
anuaralfetahe
Hello Published a new library - ProcessHub! ProcessHub is a library designed to manage process distribution within the Elixir cluster. ...
New
rodloboz
I’ve started working on a new library to run SQL queries and do basic business intelligence. Think “Blazer for Elixir.” Currently it fe...
New

Other Trending Topics Top

mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
AstonJ
This showed up on my feed.. anyone heard of it? Just hype? Ox Alpha is a reasoning model designed for coding, sustained ag...
New
bartblast
Hey folks, I just published a post about Hologram’s funding and where the project goes next - the short version: Curiosum as Main Spons...
New
CodeSync
:microphone: ElixirConf 2026 - Call for Talks is open! We’re heading to Chicago :united_states: :round_pushpin: In person + virtual :d...
New
Null-logic-0
What IDE or editor are you using for Elixir development? Personally, I use Zed, and I really like it, but sometimes I wish there were a ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews