SlideShare a Scribd company logo
HANDLING EXTERNAL
APIS WITH ELIXIR
ALEX ROZUMII
ТЕКСТ
WHY?
▸ Because:
▸ External API fail (50x)
▸ Network fails
▸ Have rate limits
Handling external APIs with Elixir - Alex Rozumii
Handling external APIs with Elixir - Alex Rozumii
TelegramInterface.pull_messages(Keyword.get(state, :offset, 0))
Enum.each(items, fn(update) ->
case update do
%Nadia.Model.Update{message: %Nadia.Model.Message{date: the_date}} ->
#IT WORKS
_ ->
Rollbax.report()
end
end
end
case Dota.live_league_games do
{:ok, curr_state} ->
# REAL LOGIC
{:noreply, tick(prev_state, curr_state)}
{:error, %Nadia.Model.Error{reason: :connect_timeout}} ->
Process.send_after(self, :timer_event, @wait_ms_before_next_polling_error)
{:noreply, tick(prev_state, prev_state)}
{:error, {:error, %HTTPoison.Error{id: nil, reason: _reason}}} ->
Process.send_after(self, :timer_event, @wait_ms_before_next_empty_response)
{:noreply, tick(prev_state, prev_state)}
{:error, {:ok, %HTTPoison.Response{status_code: 500}}} ->
Process.send_after(self, :timer_event, @wait_ms_before_next_500_error)
{:noreply, tick(prev_state, prev_state)}
end
Handling external APIs with Elixir - Alex Rozumii
ТЕКСТ
HOW?
▸ OTP
▸ Agents
▸ Behaviours
defmodule Telegram.MessageQueue do
def start_link do
Agent.start_link(fn -> [] end, name: __MODULE__)
end
# @doc Flushes all existing records
def flush! do
Agent.cast(__MODULE__, fn(_) -> [] end)
end
# @doc Pushes message for given receiver to queue
def push_message(tlg_id, message, opts) do
item = {tlg_id, message, opts}
# Agent.get(GosuObs.Telegram.MessageQueue, fn set -> set end)
Agent.update(__MODULE__, &( [item | &1 ]))
end
# @doc Gets a top message, grouped if possible
def pull_top_message do
Agent.get_and_update(__MODULE__, fn queue ->
case List.last(queue) do
nil ->
{nil, []}
msg ->
end
end
end
end
def handle_info(:timer_event, state) do
case Telegram.MessageQueue.pull_top_message do
{tlg_id, message, opts} ->
case send_message(tlg_id, message, opts) do
:ok ->
Process.send_after(self, :timer_event, @wait_ms_before_next_message_send)
nil
:error ->
Process.send_after(self, :timer_event, @wait_ms_before_next_message_send)
nil
:wait ->
Process.send_after(self, :timer_event, @wait_ms_before_next_message_send_limit)
nil
:retry ->
Process.send_after(self, :timer_event, @wait_ms_before_next_message)
GosuObs.Telegram.MessageQueue.push_message(tlg_id, message, opts)
end
{:noreply, state}
nil ->
Process.send_after(self, :timer_event, @wait_ms_before_next_message_pull)
{:noreply, state}
end
end
defp send_message(t, message, opts) do
case Nadia.send_message(t, message, opts) do
{:ok, _result} ->
:ok
{:error, %Nadia.Model.Error{reason: "Please wait»}} ->
:wait
result ->
Rollbax.report()
:retry
end
end
Handling external APIs with Elixir - Alex Rozumii
THANKS!

More Related Content

What's hot (17)

PDF
ZendCon 2017 - Build a Bot Workshop - Async Primer
Adam Englander
 
DOCX
MassChangeCORPEmail
Daniel Gilhousen
 
PDF
Concurrecny inf sharp
Riccardo Terrell
 
PPTX
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
Tim Chaplin
 
PPTX
Using Visual Studio to build XAML Universal Apps
Pranav Ainavolu
 
PDF
Actor Clustering with Docker Containers and Akka.Net in F#
Riccardo Terrell
 
PPTX
Sharding and Load Balancing in Scala - Twitter's Finagle
Geoff Ballinger
 
PDF
Akka and futures
Knoldus Inc.
 
PPTX
Workshop: Async and Parallel in C#
Rainer Stropek
 
PDF
1時間で作るマッシュアップサービス(関西版)
Yuichiro MASUI
 
PDF
Remote Config REST API and Versioning
Jumpei Matsuda
 
PDF
Confident Refactoring - Ember SF Meetup
Fastly
 
PDF
Redux Action Creators
Konstantins Starovoitovs
 
PPTX
Async ASP.NET Applications
Shayne Boyer
 
PDF
Ecmwf instructions slideshare
Nadezda Avanessova
 
PPTX
Araport Workshop Tutorial 2: Authentication and the Agave Profiles Service
stevemock
 
PDF
Using MCollective with Chef - cfgmgmtcamp.eu 2014
Zachary Stevens
 
ZendCon 2017 - Build a Bot Workshop - Async Primer
Adam Englander
 
MassChangeCORPEmail
Daniel Gilhousen
 
Concurrecny inf sharp
Riccardo Terrell
 
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
Tim Chaplin
 
Using Visual Studio to build XAML Universal Apps
Pranav Ainavolu
 
Actor Clustering with Docker Containers and Akka.Net in F#
Riccardo Terrell
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Geoff Ballinger
 
Akka and futures
Knoldus Inc.
 
Workshop: Async and Parallel in C#
Rainer Stropek
 
1時間で作るマッシュアップサービス(関西版)
Yuichiro MASUI
 
Remote Config REST API and Versioning
Jumpei Matsuda
 
Confident Refactoring - Ember SF Meetup
Fastly
 
Redux Action Creators
Konstantins Starovoitovs
 
Async ASP.NET Applications
Shayne Boyer
 
Ecmwf instructions slideshare
Nadezda Avanessova
 
Araport Workshop Tutorial 2: Authentication and the Agave Profiles Service
stevemock
 
Using MCollective with Chef - cfgmgmtcamp.eu 2014
Zachary Stevens
 

Similar to Handling external APIs with Elixir - Alex Rozumii (20)

PDF
Celery with python
Alexandre González Rodríguez
 
ODP
Building a Cloud API Server using Play(SCALA) & Riak
RajthilakMCA
 
PDF
Centralize your Business Logic with Pipelines in Elixir
Michael Viveros
 
KEY
Polyglot parallelism
Phillip Toland
 
ODP
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
dantleech
 
PDF
Let it crash - fault tolerance in Elixir/OTP
Maciej Kaszubowski
 
PDF
Design Summit - Rails 4 Migration - Aaron Patterson
ManageIQ
 
PPTX
Tools for Making Machine Learning more Reactive
Jeff Smith
 
PPT
"Scala in Goozy", Alexey Zlobin
Vasil Remeniuk
 
PDF
Implementações paralelas
Willian Molinari
 
PDF
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Masahiro Nagano
 
PDF
From polling to real time: Scala, Akka, and Websockets from scratch
Sergi González Pérez
 
PDF
GenServer in action
Yurii Bodarev
 
PDF
GenServer in Action – Yurii Bodarev
Elixir Club
 
PDF
SproutCore and the Future of Web Apps
Mike Subelsky
 
PDF
Metrics-Driven Engineering
Mike Brittain
 
PDF
Threads, Queues, and More: Async Programming in iOS
TechWell
 
PDF
Managing Large-scale Networks with Trigger
jathanism
 
PPTX
Apex code benchmarking
purushottambhaigade
 
PPTX
Random numbers
Positive Hack Days
 
Celery with python
Alexandre González Rodríguez
 
Building a Cloud API Server using Play(SCALA) & Riak
RajthilakMCA
 
Centralize your Business Logic with Pipelines in Elixir
Michael Viveros
 
Polyglot parallelism
Phillip Toland
 
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
dantleech
 
Let it crash - fault tolerance in Elixir/OTP
Maciej Kaszubowski
 
Design Summit - Rails 4 Migration - Aaron Patterson
ManageIQ
 
Tools for Making Machine Learning more Reactive
Jeff Smith
 
"Scala in Goozy", Alexey Zlobin
Vasil Remeniuk
 
Implementações paralelas
Willian Molinari
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Masahiro Nagano
 
From polling to real time: Scala, Akka, and Websockets from scratch
Sergi González Pérez
 
GenServer in action
Yurii Bodarev
 
GenServer in Action – Yurii Bodarev
Elixir Club
 
SproutCore and the Future of Web Apps
Mike Subelsky
 
Metrics-Driven Engineering
Mike Brittain
 
Threads, Queues, and More: Async Programming in iOS
TechWell
 
Managing Large-scale Networks with Trigger
jathanism
 
Apex code benchmarking
purushottambhaigade
 
Random numbers
Positive Hack Days
 
Ad

More from Elixir Club (20)

PDF
Kubernetes + Docker + Elixir - Alexei Sholik, Andrew Dryga | Elixir Club Ukraine
Elixir Club
 
PDF
Integrating 3rd parties with Ecto - Eduardo Aguilera | Elixir Club Ukraine
Elixir Club
 
PDF
— An async template - Oleksandr Khokhlov | Elixir Club Ukraine
Elixir Club
 
PDF
BEAM architecture handbook - Andrea Leopardi | Elixir Club Ukraine
Elixir Club
 
PDF
You ain't gonna need write a GenServer - Ulisses Almeida | Elixir Club Ukraine
Elixir Club
 
PDF
— Knock, knock — An async templates — Who’s there? - Alexander Khokhlov | ...
Elixir Club
 
PDF
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Elixir Club
 
PDF
Erlang cluster. How is it? Production experience. — Valerii Vasylkov | Elixi...
Elixir Club
 
PDF
Promo Phx4RailsDevs - Volodya Sveredyuk
Elixir Club
 
PDF
Web of today — Alexander Khokhlov
Elixir Club
 
PDF
ElixirConf Eu 2018, what was it like? – Eugene Pirogov
Elixir Club
 
PDF
Implementing GraphQL API in Elixir – Victor Deryagin
Elixir Club
 
PDF
WebPerformance: Why and How? – Stefan Wintermeyer
Elixir Club
 
PDF
Russian Doll Paradox: Elixir Web without Phoenix - Alex Rozumii
Elixir Club
 
PDF
Practical Fault Tolerance in Elixir - Alexei Sholik
Elixir Club
 
PDF
Phoenix and beyond: Things we do with Elixir - Alexander Khokhlov
Elixir Club
 
PDF
Monads are just monoids in the category of endofunctors - Ike Kurghinyan
Elixir Club
 
PDF
Craft effective API with GraphQL and Absinthe - Ihor Katkov
Elixir Club
 
PDF
Elixir in a service of government - Alex Troush
Elixir Club
 
PDF
Pattern matching in Elixir by example - Alexander Khokhlov
Elixir Club
 
Kubernetes + Docker + Elixir - Alexei Sholik, Andrew Dryga | Elixir Club Ukraine
Elixir Club
 
Integrating 3rd parties with Ecto - Eduardo Aguilera | Elixir Club Ukraine
Elixir Club
 
— An async template - Oleksandr Khokhlov | Elixir Club Ukraine
Elixir Club
 
BEAM architecture handbook - Andrea Leopardi | Elixir Club Ukraine
Elixir Club
 
You ain't gonna need write a GenServer - Ulisses Almeida | Elixir Club Ukraine
Elixir Club
 
— Knock, knock — An async templates — Who’s there? - Alexander Khokhlov | ...
Elixir Club
 
Performance measurement methodology — Maksym Pugach | Elixir Evening Club 3
Elixir Club
 
Erlang cluster. How is it? Production experience. — Valerii Vasylkov | Elixi...
Elixir Club
 
Promo Phx4RailsDevs - Volodya Sveredyuk
Elixir Club
 
Web of today — Alexander Khokhlov
Elixir Club
 
ElixirConf Eu 2018, what was it like? – Eugene Pirogov
Elixir Club
 
Implementing GraphQL API in Elixir – Victor Deryagin
Elixir Club
 
WebPerformance: Why and How? – Stefan Wintermeyer
Elixir Club
 
Russian Doll Paradox: Elixir Web without Phoenix - Alex Rozumii
Elixir Club
 
Practical Fault Tolerance in Elixir - Alexei Sholik
Elixir Club
 
Phoenix and beyond: Things we do with Elixir - Alexander Khokhlov
Elixir Club
 
Monads are just monoids in the category of endofunctors - Ike Kurghinyan
Elixir Club
 
Craft effective API with GraphQL and Absinthe - Ihor Katkov
Elixir Club
 
Elixir in a service of government - Alex Troush
Elixir Club
 
Pattern matching in Elixir by example - Alexander Khokhlov
Elixir Club
 
Ad

Recently uploaded (20)

PDF
Upskill to Agentic Automation 2025 - Kickoff Meeting
DianaGray10
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PDF
Arcee AI - building and working with small language models (06/25)
Julien SIMON
 
PDF
Shuen Mei Parth Sharma Boost Productivity, Innovation and Efficiency wit...
AWS Chicago
 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PDF
Français Patch Tuesday - Juillet
Ivanti
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PPTX
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PPTX
Top Managed Service Providers in Los Angeles
Captain IT
 
PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
PDF
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
PDF
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
Upskill to Agentic Automation 2025 - Kickoff Meeting
DianaGray10
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Arcee AI - building and working with small language models (06/25)
Julien SIMON
 
Shuen Mei Parth Sharma Boost Productivity, Innovation and Efficiency wit...
AWS Chicago
 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
Français Patch Tuesday - Juillet
Ivanti
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Top Managed Service Providers in Los Angeles
Captain IT
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 

Handling external APIs with Elixir - Alex Rozumii

  • 1. HANDLING EXTERNAL APIS WITH ELIXIR ALEX ROZUMII
  • 2. ТЕКСТ WHY? ▸ Because: ▸ External API fail (50x) ▸ Network fails ▸ Have rate limits
  • 5. TelegramInterface.pull_messages(Keyword.get(state, :offset, 0)) Enum.each(items, fn(update) -> case update do %Nadia.Model.Update{message: %Nadia.Model.Message{date: the_date}} -> #IT WORKS _ -> Rollbax.report() end end end
  • 6. case Dota.live_league_games do {:ok, curr_state} -> # REAL LOGIC {:noreply, tick(prev_state, curr_state)} {:error, %Nadia.Model.Error{reason: :connect_timeout}} -> Process.send_after(self, :timer_event, @wait_ms_before_next_polling_error) {:noreply, tick(prev_state, prev_state)} {:error, {:error, %HTTPoison.Error{id: nil, reason: _reason}}} -> Process.send_after(self, :timer_event, @wait_ms_before_next_empty_response) {:noreply, tick(prev_state, prev_state)} {:error, {:ok, %HTTPoison.Response{status_code: 500}}} -> Process.send_after(self, :timer_event, @wait_ms_before_next_500_error) {:noreply, tick(prev_state, prev_state)} end
  • 9. defmodule Telegram.MessageQueue do def start_link do Agent.start_link(fn -> [] end, name: __MODULE__) end # @doc Flushes all existing records def flush! do Agent.cast(__MODULE__, fn(_) -> [] end) end # @doc Pushes message for given receiver to queue def push_message(tlg_id, message, opts) do item = {tlg_id, message, opts} # Agent.get(GosuObs.Telegram.MessageQueue, fn set -> set end) Agent.update(__MODULE__, &( [item | &1 ])) end # @doc Gets a top message, grouped if possible def pull_top_message do Agent.get_and_update(__MODULE__, fn queue -> case List.last(queue) do nil -> {nil, []} msg -> end end end end
  • 10. def handle_info(:timer_event, state) do case Telegram.MessageQueue.pull_top_message do {tlg_id, message, opts} -> case send_message(tlg_id, message, opts) do :ok -> Process.send_after(self, :timer_event, @wait_ms_before_next_message_send) nil :error -> Process.send_after(self, :timer_event, @wait_ms_before_next_message_send) nil :wait -> Process.send_after(self, :timer_event, @wait_ms_before_next_message_send_limit) nil :retry -> Process.send_after(self, :timer_event, @wait_ms_before_next_message) GosuObs.Telegram.MessageQueue.push_message(tlg_id, message, opts) end {:noreply, state} nil -> Process.send_after(self, :timer_event, @wait_ms_before_next_message_pull) {:noreply, state} end end
  • 11. defp send_message(t, message, opts) do case Nadia.send_message(t, message, opts) do {:ok, _result} -> :ok {:error, %Nadia.Model.Error{reason: "Please wait»}} -> :wait result -> Rollbax.report() :retry end end