An Elixir microservice in front of the SellerMagnet API validates every request before it can spend a credit, answers repeat lookups from a short-lived public-ETS cache, and retries only the status codes a second attempt can fix. This guide builds that wrapper on Plug - the same minimal HTTP toolkit Phoenix itself is built on, used directly here since a full Phoenix project generator needs a newer Elixir release than this box ships. Wrapper.Validate, Wrapper.Cache and Wrapper.Router are new, and the Elixir quickstart's own client.ex, retry.ex and product.ex are reused completely unchanged - and tests all of it against the real Plug router and a fails-closed fake HTTP server so nothing here is just described.
Key Takeaways
- Validate asin and marketplaceId in Wrapper.Validate before the upstream call, so a bad request costs nothing and waits on no timeout.
- A public ETS table (read_concurrency: true) answers a repeated lookup for free; it lives in one BEAM node, so several nodes behind a load balancer each keep their own copy unless you add a shared store.
- client.ex, retry.ex and product.ex from the Elixir quickstart are reused byte-identical: a Plug router needs no package rewrite the way Spring Boot's component scan does.
- The retry policy is the quickstart's own: 429 waits for free, a 500 is retried once (it is refunded), 502/503 are retried up to 4 times (each billed), and a 404 is a real answer, never retried.
- A connection refusal reaches Client.get_once/3 as {:error, {:http, reason}}, not an {:api, status, ...} tuple - Retry.get/3 (reused unchanged) does not retry that shape at all, so it surfaces immediately with 0 credits billed, unlike a real upstream status code.
Why wrap the API in a microservice instead of calling it directly?
A thin service in front of the API gives every caller in a larger system one place that enforces the request shape, one cache for ASINs several callers ask for repeatedly, and one retry policy, instead of each caller reimplementing the Elixir quickstart's client.ex and retry.ex on its own. This post reuses that exact client and retry helper unchanged - :httpc from Erlang's own :inets needs nothing async-specific to sit behind a Plug router, so there is no separate async client to maintain here.
setup.sh - Plug + Cowboy added to mix.exs, no Phoenix generator needed
elixir --version # Elixir 1.14+, OTP ships :inets/:ssl/:public_key
mix new wrapper --sup && cd wrapper
# add {:plug_cowboy, "~> 2.6"} and {:jason, "~> 1.4"} to deps() in mix.exs
mix local.hex --force && mix local.rebar --force && mix deps.get
export SELLERMAGNET_API_KEY="your-key-here"
# save lib/sellermagnet/{client,retry,product}.ex (unchanged from the quickstart) and
# lib/wrapper/{cache,validate,router,application}.ex from this post, then:
PORT=8098 mix run --no-halt
How do I validate the ASIN and marketplaceId before spending a credit?
Normalize first, then check the shape: trim and upper-case the ASIN before testing it against Product.asin?/1 (the quickstart's own \A...\z-anchored regex, reused unchanged), and trim the marketplace ID before testing membership in a small MapSet. The full list of all 23 marketplace IDs is in the marketplace IDs list; this wrapper only turns on the same four this family's Spring Boot and NestJS siblings use. Both checks run before any call to SellerMagnet.Client, and lookup_params/2 returns one error entry per failing field rather than a single combined message, so a caller can tell exactly which field was wrong.
lib/wrapper/validate.ex - validated before any network call
defmodule Wrapper.Validate do
@moduledoc """
Request validation at the HTTP boundary, run before any upstream call: a bad ASIN shape or an
unsupported marketplaceId never reaches SellerMagnet.Client, so it never spends a credit and
never waits on the 120-second timeout. Normalizing (trim + upcase the ASIN) happens here,
BEFORE the shape check, the same order the Python/Java quickstarts' own validators use.
The full list of all 23 marketplace IDs is at
https://sellermagnet-api.com/blog/amazon-marketplace-ids-list - this wrapper only turns on
the handful below, same set as the Spring Boot/NestJS/Sinatra siblings in this family.
"""
alias SellerMagnet.Product
@supported_marketplaces MapSet.new([
# amazon.com
"ATVPDKIKX0DER",
# amazon.de
"A1PA6795UKMFR9",
# amazon.co.uk
"A1F83G8C2ARO7P",
# amazon.fr
"A13V1IB3VIYZZH"
])
@doc """
{:ok, {asin, marketplace_id}} with asin trimmed+upper-cased, or {:error, [detail, ...]} with
one entry per failing field (never a single combined message, so a caller can tell which
field was wrong).
"""
def lookup_params(raw_asin, raw_marketplace_id) do
asin = normalize_asin(raw_asin)
marketplace_id = String.trim(raw_marketplace_id || "")
errors =
[]
|> maybe_add(not Product.asin?(asin), %{"loc" => "asin", "msg" => "asin must be 10 upper-case letters/digits"})
|> maybe_add(not MapSet.member?(@supported_marketplaces, marketplace_id), %{
"loc" => "marketplaceId",
"msg" => "unknown marketplaceId"
})
if errors == [] do
{:ok, {asin, marketplace_id}}
else
{:error, errors}
end
end
defp normalize_asin(nil), do: ""
defp normalize_asin(value), do: value |> String.trim() |> String.upcase()
defp maybe_add(errors, true, detail), do: [detail | errors]
defp maybe_add(errors, false, _detail), do: errors
end
How does the cache avoid paying twice for the same ASIN?
Wrapper.Cache owns a public, named ETS table (read_concurrency: true) keyed by "asin:marketplaceId", with each entry carrying its own expiry in System.monotonic_time(:millisecond). A lookup within the TTL (300 seconds here) returns the stored result with cached: true and makes no network call at all; a lookup after the TTL, or for a key never seen, falls through to the upstream call and refreshes the entry. Because the table is public, every Cowboy acceptor process reads and writes it directly - the GenServer only owns the table so it survives any single request process crashing, it is never on the read/write path itself. This cache lives on the BEAM node that holds it: with several nodes behind a load balancer, each one keeps its own copy, so the same ASIN can still be fetched once per node. That trade-off is deliberate here - a shared cache needs an external store a reader picks for their own deployment, which this post does not assume or name.
lib/wrapper/cache.ex - a public-ETS TTL cache
defmodule Wrapper.Cache do
@moduledoc """
A tiny in-process TTL cache, keyed by "asin:marketplaceId", backed by a public ETS table
(read_concurrency: true) so every Cowboy acceptor process reads/writes it directly with no
message-passing round trip through this GenServer; the GenServer only owns the table so it
survives any single request process crashing.
Not a cross-process cache (no external cache store named here, per the owner's
infrastructure rule): one BEAM node holds its own table. Running several nodes behind a load
balancer means each keeps its own copy, so the same ASIN can be fetched once per node within
the TTL window.
"""
use GenServer
@table __MODULE__
def start_link(opts \\ []), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
@impl true
def init(_opts) do
:ets.new(@table, [:set, :public, :named_table, read_concurrency: true])
{:ok, %{}}
end
@doc "nil on a miss or an expired entry (and the stale entry is dropped)."
def get(key) do
case :ets.lookup(@table, key) do
[{^key, value, expires_at}] ->
if System.monotonic_time(:millisecond) < expires_at do
value
else
:ets.delete(@table, key)
nil
end
[] ->
nil
end
end
def put(key, value, ttl_ms) do
expires_at = System.monotonic_time(:millisecond) + ttl_ms
:ets.insert(@table, {key, value, expires_at})
value
end
@doc "Test-only convenience: starts the next scenario from an empty cache."
def clear do
:ets.delete_all_objects(@table)
end
def size, do: :ets.info(@table, :size)
end
What does the router itself look like?
Wrapper.client/0 builds a fresh SellerMagnet.Client on every call by reading SELLERMAGNET_API_KEY/SELLERMAGNET_API_BASE at call time - the same constructor seam the quickstart's own main.exs already uses, which lets tests point the base at a local fake AFTER the application's own supervision tree is already running. The router validates the path and query parameters first, checks the cache, and only then calls SellerMagnet.Product.lookup/3 (which itself calls SellerMagnet.Retry.get/4, unchanged). A transport-level failure surfaces as {:error, {:http, reason}} from SellerMagnet.Client, a different shape than the {:api, status, ...} tuples SellerMagnet.Retry retries, so it needs its own case branch or it would never match any of the clauses that handle a real upstream answer.
lib/wrapper/router.ex - the Plug microservice
defmodule Wrapper.Router do
@moduledoc """
The Plug microservice wrapping the SellerMagnet API's product lookup. Validates the request
(Wrapper.Validate) before any network call, serves repeat lookups from a short-lived
in-process cache (Wrapper.Cache), and only then calls the upstream API through the reused
SellerMagnet.Client / SellerMagnet.Retry / SellerMagnet.Product from the Elixir quickstart,
unchanged.
"""
use Plug.Router
@cache_ttl_ms 300_000
plug :match
plug :fetch_query_params
plug :dispatch
get "/lookup/:asin" do
marketplace_id = conn.query_params["marketplaceId"]
case Wrapper.Validate.lookup_params(asin, marketplace_id) do
{:error, detail} ->
send_json(conn, 422, %{"detail" => detail})
{:ok, {normalized_asin, normalized_marketplace}} ->
cache_key = normalized_asin <> ":" <> normalized_marketplace
case Wrapper.Cache.get(cache_key) do
nil -> lookup_upstream(conn, normalized_asin, normalized_marketplace, cache_key)
hit -> send_json(conn, 200, Map.put(hit, "cached", true))
end
end
end
match _ do
send_json(conn, 404, %{"detail" => "no such route"})
end
defp lookup_upstream(conn, asin, marketplace_id, cache_key) do
client = Wrapper.client()
case SellerMagnet.Product.lookup(client, asin, marketplace_id) do
{:ok, %{price: price, currency: currency}} ->
body = %{"asin" => asin, "marketplaceId" => marketplace_id, "price" => price, "currency" => currency, "cached" => false}
Wrapper.Cache.put(cache_key, body, @cache_ttl_ms)
send_json(conn, 200, body)
{:error, {:api, 404, message, _retry_after}} ->
# A real answer from upstream: billed once, never retried, never a 5xx.
send_json(conn, 404, %{"detail" => message})
{:error, {:api, status, _message, _retry_after}} when status in [400, 401, 403] ->
send_json(conn, 502, %{"detail" => "upstream lookup failed"})
{:error, {:api, _status, _message, _retry_after}} ->
# Retries already exhausted inside SellerMagnet.Retry (429/500/502/503 all handled
# there, unchanged); whatever reaches here is a final failure, reported as 502.
send_json(conn, 502, %{"detail" => "upstream lookup failed"})
{:error, {:http, _reason}} ->
# The connection itself never completed (e.g. econnrefused): nothing was billed, and
# SellerMagnet.Retry (reused unchanged) does not retry a transport-level error, only
# an {:api, status, ...} answer - so this surfaces immediately as its own branch.
send_json(conn, 502, %{"detail" => "upstream unreachable"})
end
end
defp send_json(conn, status, body) do
conn
|> put_resp_content_type("application/json")
|> send_resp(status, Jason.encode!(body))
end
end
lib/wrapper/application.ex - supervises the cache's ETS owner and Cowboy
defmodule Wrapper.Application do
@moduledoc """
Supervises the TTL cache's ETS owner and Cowboy. The upstream SellerMagnet.Client is built
lazily per request (Wrapper.client/0) so tests can point SELLERMAGNET_API_BASE at a fake
server started AFTER the application tree is already running.
"""
use Application
@impl true
def start(_type, _args) do
port = String.to_integer(System.get_env("PORT", "8098"))
children = [
Wrapper.Cache,
{Plug.Cowboy, scheme: :http, plug: Wrapper.Router, options: [port: port]}
]
Supervisor.start_link(children, strategy: :one_for_one, name: Wrapper.Supervisor)
end
end
A connection refusal is not retried by the reused Retry module
The first version of this wrapper's test suite assumed a connection refusal would be retried up to the same 4-attempt cap as a 502/503, the way the Spring Boot and NestJS siblings in this family handle it. mix test disagreed: SellerMagnet.Retry.get/4, reused byte-identical from the Elixir quickstart, only retries an {:error, {:api, status, _, _}} tuple whose status is in its own retryable list - a {:error, {:http, reason}} transport failure falls straight through to the other -> other clause and returns on the first attempt. Billing-wise that is correct (nothing was ever sent, so nothing could be billed), but it means a connection refusal costs exactly one attempt here, not four - the opposite of the Java/TypeScript wrappers in this family, which retry at the client's own HTTP-exception level. The post's scenario table and test suite assert the real, once-only behaviour instead of the four-attempt behaviour this family's other posts describe, because client.ex/retry.ex are reused unchanged rather than rewritten to match.

Trimmed response for a cache-miss lookup
{
"asin": "B0CL61F39H",
"marketplaceId": "ATVPDKIKX0DER",
"price": 444.99,
"currency": "USD",
"cached": false
}
| Scenario | HTTP status | Retried? | Billed? |
|---|---|---|---|
| Valid ASIN, cache miss | 200 | - | Yes (1 credit) |
| Same lookup again within 300s | 200 (cached) | no | No - 0 upstream calls |
| Malformed ASIN shape | 422 | no | No - rejected before the network |
| Unknown marketplaceId | 422 | no | No - rejected before the network |
| Lower-case ASIN, cache miss | 200 | - | Yes - normalized then looked up |
| Upstream 404 (not on this marketplace) | 404 | no | Yes - a real answer |
| Upstream 429 (concurrency cap) | 200 (after a wait) | yes - free | No - the 429 itself |
| Upstream 500 (refunded) | 200 (after 1 retry) | yes, capped at 1 | No - the 500 itself |
| Two upstream 500s in a row | 502 | no - stops | No - the 500s |
| Upstream 502 / 503 | 502 | yes, up to 4 attempts | Yes - every attempt |
| Connection refused (never reached the server) | 502 | no - not an API answer | No - nothing was billed |
| N/A price on a successful answer | 200 | - | Yes - decodes to a null price, never 0.0 |
| 20 concurrent requests for the same key | 200 x 20 | - | At most once per request, cache stays correct |

How do I fake the upstream API without spending credits in every test?
FakeServer is the same local :gen_tcp fake the Elixir mock-testing guide already built on top of the quickstart's own test seam: install/2 scripts exactly the next response, and the default (no install) answers 500 "install/2 first", so a forgotten scenario fails loudly instead of silently reaching for a plausible empty answer. The test suite points SELLERMAGNET_API_BASE at FakeServer.base_url/1 and calls Wrapper.Router.call/2 through Plug.Test - a real %Plug.Conn{} built from a real request, run through the real router pipeline (:match, :fetch_query_params, :dispatch), with only the upstream API faked.
test/support/fake_server.ex - reused byte-identical from amazon-api-mock-testing-elixir
defmodule FakeServer do
@moduledoc """
A minimal HTTP/1.1 test double over :gen_tcp (stdlib only, no Plug/Cowboy dependency): it
fails closed until install/2 scripts a route, so a request sent before installing one gets a
loud 500 instead of quietly looking like a real answer. Points the quickstart's own
SELLERMAGNET_API_BASE test seam at 127.0.0.1 - lib/sellermagnet/client.ex, retry.ex and
product.ex run completely unchanged against it. Reused byte-identical from
amazon-api-mock-testing-elixir.
"""
@doc "Starts a listener on a random free port. Returns a handle for install/2, calls/1, stop/1."
def start do
{:ok, listen} = :gen_tcp.listen(0, [:binary, packet: :line, active: false, reuseaddr: true])
{:ok, port} = :inet.port(listen)
{:ok, agent} = Agent.start_link(fn -> {nil, []} end)
acceptor = spawn(fn -> accept_loop(listen, agent) end)
%{listen: listen, port: port, agent: agent, acceptor: acceptor}
end
def stop(%{listen: listen, acceptor: acceptor}) do
Process.exit(acceptor, :kill)
:gen_tcp.close(listen)
end
@doc """
route_fun.(method, path, query, headers) -> {status, body} | {status, body, extra_headers}.
Replaces whatever route was installed before; each test installs its own and nothing leaks
across tests because every test starts a fresh server.
"""
def install(%{agent: agent}, route_fun), do: Agent.update(agent, fn {_old, calls} -> {route_fun, calls} end)
@doc "Every request the server has received so far, oldest first: {method, path, query, headers}."
def calls(%{agent: agent}), do: Agent.get(agent, fn {_route, calls} -> Enum.reverse(calls) end)
def base_url(%{port: port}), do: "http://127.0.0.1:#{port}"
defp accept_loop(listen, agent) do
case :gen_tcp.accept(listen, 200) do
{:ok, sock} ->
spawn(fn -> handle(sock, agent) end)
accept_loop(listen, agent)
{:error, :timeout} ->
accept_loop(listen, agent)
{:error, :closed} ->
:ok
end
end
defp handle(sock, agent) do
case recv_request_line(sock) do
{:ok, method, target} ->
headers = recv_headers(sock)
{path, query} = split_target(target)
route = Agent.get(agent, fn {r, _} -> r end)
Agent.update(agent, fn {r, calls} -> {r, [{method, path, query, headers} | calls]} end)
case route do
nil ->
respond(sock, 500, ~s({"success":false,"message":"fakeserver: install/2 first"}), [])
fun ->
case fun.(method, path, query, headers) do
{status, body} -> respond(sock, status, body, [])
{status, body, extra} -> respond(sock, status, body, extra)
end
end
:error ->
:ok
end
:gen_tcp.close(sock)
end
defp recv_request_line(sock) do
case :gen_tcp.recv(sock, 0, 2_000) do
{:ok, line} ->
case line |> String.trim() |> String.split(" ") do
[method, target, _version] -> {:ok, method, target}
_ -> :error
end
{:error, _} ->
:error
end
end
defp recv_headers(sock, acc \\ []) do
case :gen_tcp.recv(sock, 0, 2_000) do
{:ok, line} ->
trimmed = String.trim(line)
if trimmed == "" do
Enum.reverse(acc)
else
[name, value] = String.split(trimmed, ":", parts: 2)
recv_headers(sock, [{String.downcase(name), String.trim(value)} | acc])
end
{:error, _} ->
Enum.reverse(acc)
end
end
defp split_target(target) do
case String.split(target, "?", parts: 2) do
[path] -> {path, %{}}
[path, qs] -> {path, URI.decode_query(qs)}
end
end
defp respond(sock, status, body, extra_headers) do
base = [
"HTTP/1.1 #{status} x\r\n",
"Content-Type: application/json\r\n",
"Content-Length: #{byte_size(body)}\r\n",
"Connection: close\r\n"
]
extra = Enum.map(extra_headers, fn {k, v} -> "#{k}: #{v}\r\n" end)
:gen_tcp.send(sock, Enum.join(base ++ extra) <> "\r\n" <> body)
end
end
test/wrapper_router_test.exs - 14 scenarios against the real Plug router
defmodule WrapperRouterTest do
@moduledoc """
Fails-closed scenario tests against the real Plug router (Plug.Test builds a real %Plug.Conn{}
and WrapperRouterTest calls Wrapper.Router.call/2 exactly the way Plug.Cowboy would), with
only the upstream SellerMagnet API faked via FakeServer (:gen_tcp, reused byte-identical from
amazon-api-mock-testing-elixir). SellerMagnet.Client/Retry/Product run completely unmodified,
including their real backoff waits (via the injectable sleep_fun only inside Retry itself -
here we exercise the router's own call path, which uses Retry.get/3 with its default sleep_fun,
so these tests DO wait the real backoff milliseconds for the 429/500/502 cases, proving the
actual wait math runs, not just that the code path is reached).
"""
use ExUnit.Case, async: false
import Plug.Test
@asin "B0CL61F39H"
@marketplace "ATVPDKIKX0DER"
setup do
server = FakeServer.start()
System.put_env("SELLERMAGNET_API_KEY", "test-key")
System.put_env("SELLERMAGNET_API_BASE", FakeServer.base_url(server) <> "/api")
Wrapper.Cache.clear()
on_exit(fn ->
FakeServer.stop(server)
System.delete_env("SELLERMAGNET_API_BASE")
end)
%{server: server}
end
defp ok_envelope(price, currency \\ "USD") do
~s({"success":true,"data":{"productInfo":{"buyBoxInfo":{"price":#{inspect(price)},"currencyCode":#{inspect(currency)}}}}})
end
defp get(path) do
conn(:get, path) |> Wrapper.Router.call([])
end
# --- 1. valid lookup, cache miss -------------------------------------------------------------
test "valid asin + marketplace, cache miss, 200 with price", %{server: server} do
FakeServer.install(server, fn _m, _p, _q, _h -> {200, ok_envelope(444.99)} end)
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 200
body = Jason.decode!(conn.resp_body)
assert body["price"] == 444.99
assert body["currency"] == "USD"
assert body["cached"] == false
assert length(FakeServer.calls(server)) == 1
end
# --- 2. same lookup again within the TTL window: served from cache, 0 upstream calls --------
test "second identical lookup is served from cache, no second upstream call", %{server: server} do
FakeServer.install(server, fn _m, _p, _q, _h -> {200, ok_envelope(444.99)} end)
get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
second = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
body = Jason.decode!(second.resp_body)
assert second.status == 200
assert body["cached"] == true
assert length(FakeServer.calls(server)) == 1
end
# --- 3. malformed ASIN shape never reaches the network ---------------------------------------
test "malformed asin is rejected before any upstream call", %{server: server} do
conn = get("/lookup/not-an-asin?marketplaceId=#{@marketplace}")
assert conn.status == 422
assert Jason.decode!(conn.resp_body)["detail"] != []
assert FakeServer.calls(server) == []
end
# --- 4. unknown marketplaceId never reaches the network ---------------------------------------
test "unknown marketplaceId is rejected before any upstream call", %{server: server} do
conn = get("/lookup/#{@asin}?marketplaceId=A2Q3Y263D00KWC")
assert conn.status == 422
assert FakeServer.calls(server) == []
end
# --- 5. a lower-case ASIN is normalized then looked up ---------------------------------------
test "lower-case asin is normalized to upper-case before lookup", %{server: server} do
FakeServer.install(server, fn _m, _p, _q, _h -> {200, ok_envelope(444.99)} end)
conn = get("/lookup/#{String.downcase(@asin)}?marketplaceId=#{@marketplace}")
assert conn.status == 200
assert Jason.decode!(conn.resp_body)["asin"] == @asin
end
# --- 6. upstream 404 passes through as a real answer, never a 500/502 ------------------------
test "upstream 404 passes through as its own real answer", %{server: server} do
FakeServer.install(server, fn _m, _p, _q, _h ->
{404, ~s({"success":false,"message":"Invalid product"})}
end)
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 404
assert length(FakeServer.calls(server)) == 1
end
# --- 7. free 429 is retried (honouring Retry-After) and eventually succeeds ------------------
test "429 is retried and eventually succeeds", %{server: server} do
{:ok, agent} = Agent.start_link(fn -> 0 end)
FakeServer.install(server, fn _m, _p, _q, _h ->
n = Agent.get_and_update(agent, fn n -> {n, n + 1} end)
if n == 0 do
{429, ~s({"success":false,"message":"rate limited"}), [{"Retry-After", "0"}]}
else
{200, ok_envelope(444.99)}
end
end)
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 200
assert length(FakeServer.calls(server)) == 2
end
# --- 8. a single refunded 500 is retried once and then succeeds ------------------------------
test "a single 500 is retried once and then succeeds", %{server: server} do
{:ok, agent} = Agent.start_link(fn -> 0 end)
FakeServer.install(server, fn _m, _p, _q, _h ->
n = Agent.get_and_update(agent, fn n -> {n, n + 1} end)
if n == 0, do: {500, ~s({"success":false,"message":"internal error"})}, else: {200, ok_envelope(444.99)}
end)
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 200
assert length(FakeServer.calls(server)) == 2
end
# --- 9. two consecutive 500s stop instead of looping, reported as 502 ------------------------
test "two consecutive 500s stop and surface as 502", %{server: server} do
FakeServer.install(server, fn _m, _p, _q, _h -> {500, ~s({"success":false,"message":"internal error"})} end)
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 502
assert length(FakeServer.calls(server)) == 2
end
# --- 10. 502/503 are billed and retried up to the attempt cap, then surfaced as 502 ----------
test "502 is retried up to the attempt cap then surfaced as 502", %{server: server} do
FakeServer.install(server, fn _m, _p, _q, _h -> {502, ~s({"success":false,"message":"upstream error"})} end)
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 502
assert length(FakeServer.calls(server)) == 4
end
# --- 11. connection refused (upstream never reached): 0 credits billed, surfaced as 502 ------
test "connection refused never bills a credit and surfaces as 502" do
System.put_env("SELLERMAGNET_API_BASE", "http://127.0.0.1:1/api")
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 502
assert Jason.decode!(conn.resp_body)["detail"] == "upstream unreachable"
end
# --- 12. "N/A" price stays null, never coerced to 0.0 -----------------------------------------
test "an N/A price decodes to a null price, never 0.0 or a crash", %{server: server} do
FakeServer.install(server, fn _m, _p, _q, _h ->
{200, ~s({"success":true,"data":{"productInfo":{"buyBoxInfo":{"price":"N/A","currencyCode":null}}}})}
end)
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 200
assert Jason.decode!(conn.resp_body)["price"] == nil
end
# --- 13. a 20-process concurrent cache read/write stays correct on the public ETS table ------
test "concurrent cache reads for the same key stay correct under load", %{server: server} do
FakeServer.install(server, fn _m, _p, _q, _h -> {200, ok_envelope(444.99)} end)
tasks =
for _ <- 1..20 do
Task.async(fn -> get("/lookup/#{@asin}?marketplaceId=#{@marketplace}") end)
end
results = Enum.map(tasks, &Task.await/1)
assert Enum.all?(results, &(&1.status == 200))
# At least one upstream call happened; the exact count depends on the race between the
# first few requests before the cache is populated, but it must never exceed 20 and the
# cache must have exactly one entry afterwards (no corruption from concurrent ets writes).
assert Wrapper.Cache.size() == 1
assert length(FakeServer.calls(server)) <= 20
end
# --- 14. fails closed: a request before any route is installed gets a loud, mapped failure --
test "fails closed before any fake route is installed", %{server: _server} do
conn = get("/lookup/#{@asin}?marketplaceId=#{@marketplace}")
assert conn.status == 502
end
end
Real output: mix test, all 14 scenarios, real retry waits included
$ mix test
..............
Finished in 6.4 seconds (0.00s async, 6.4s sync)
14 tests, 0 failures
Real output: mix run, a cache miss then a cache hit, one upstream call total
$ curl "http://127.0.0.1:8098/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER"
{"asin":"B0CL61F39H","cached":false,"currency":"USD","marketplaceId":"ATVPDKIKX0DER","price":444.99}
$ curl "http://127.0.0.1:8098/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER" # again, within the 300s cache window
{"asin":"B0CL61F39H","cached":true,"currency":"USD","marketplaceId":"ATVPDKIKX0DER","price":444.99}
$ curl -o /dev/null -w "%{http_code}\n" "http://127.0.0.1:8098/lookup/bad-asin?marketplaceId=ATVPDKIKX0DER"
422
This cache is per BEAM node
Running the service as several nodes behind a load balancer means each one holds its own ETS table, so the same ASIN can be fetched once per node within the TTL. That is a reasonable default for a single small service; a reader running several nodes should size the TTL around that, or swap in a shared store of their own choice, which this post does not assume or name.
Frequently Asked Questions
Why Plug instead of a full Phoenix project?
Plug is the HTTP toolkit Phoenix itself is built on, and it is enough for a single-route wrapper on its own. Generating a project with mix phx.new specifically needs Elixir ~> 1.17; this post targets the 1.14/OTP 25 combination the quickstart series already uses, so Plug plus Cowboy is used directly instead.
Does the cache in this wrapper work across multiple BEAM nodes?
No. Wrapper.Cache wraps a plain named ETS table local to one node; each node keeps its own copy. Several nodes sharing one cache need a shared store of their own choosing, which is outside this post's scope.
Which status codes does the wrapper retry?
429 is waited out for free, a 500 is retried once since it is refunded, and 502/503 are retried up to 4 attempts total since each is billed. A 404 is a real answer and is never retried. A connection refusal is a transport-level failure, not an API status code, so SellerMagnet.Retry (reused unchanged) does not retry it at all.
Why does client.ex/retry.ex/product.ex need zero changes when NestJS's sellermagnet.ts needed none either, but Spring Boot's needed a package line?
A Plug router has no component-scan step the way Spring Boot does, so there is nothing that breaks by sitting in a particular module namespace. The quickstart's three files are require'd (or compiled as ordinary modules) exactly as written.
Is a public ETS table safe for concurrent writers without extra locking?
Yes for this cache's access pattern: :ets.insert/2 on a :set table is atomic per key, so two concurrent writers for the same key never corrupt the table, they just race on which value wins - acceptable for a cache where either answer is a valid (if slightly stale) one.
Bottom line: validate with a plain function before any network call, cache repeat lookups for free in a short-lived public-ETS table, and reuse the quickstart's own client and retry policy completely unchanged, including the exact shape of a transport failure it does not retry. Every behaviour here, including the connection-refusal callout the test suite caught, came from running mix test against real code with only the upstream HTTP layer faked - see the Elixir quickstart for the client's own retry details and the API documentation for every endpoint.