Skip to content

Instantly share code, notes, and snippets.

@towhans
Last active March 14, 2024 13:46
Show Gist options
  • Save towhans/87f118de63688fb0b4e5b412a19f7f4d to your computer and use it in GitHub Desktop.
Save towhans/87f118de63688fb0b4e5b412a19f7f4d to your computer and use it in GitHub Desktop.
Rate Limit na volani externiho API

Rate Limit na volani externiho API

image

Nekdy potrebujete nepretizit externi API svymi pozadavky. Podivame se na jednoduchy zpusob, jak to provest pomoci knihovny jobs od Ulf Wiggera.

Externi API ma problem, kdyz mu posleme vic nez 5 pozadavku za vterinu. Takze potrebujeme omezit pocet volani na 5 za sekundu.

Zaroven chceme po obdrzeni odpovedi z API pokracovat tam, kde jsme prestali. Na to pouzijeme klasicky Beamovsky send & receive. Timto zpusobem muzeme API volat klidne z 50 jinych procesu a mame zaruceno, ze externi API nepretizime. Zaroven API vyuzivame na 100% jeho moznosti.

mix.exs

    {:jobs, "~> 0.10.0"}

application.ex

    :jobs.add_queue(:rate_limited_queue, [ {:regulators, [{ :rate, [{:limit, 5}]}]}])

nekde v kodu

  def rate_limited_action(params) do
    pid = self()
    :jobs.run(:rate_limited_queue, fn ->
      send(pid, {:queue_response, action(params)})
    end)
    receive do
      {:queue_response, result} ->
        result
      _ ->
        {:error, :unexpected_status_from_rate_limited_queue}
    after
      30_000 ->
        {:error, :timeout_of_from_rate_limited_queue}
    end
  end

Odkazy:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment