A Ruby Sinatra microservice in front of the SellerMagnet API validates every request with a regex and a Hash membership check before it can spend a credit, answers repeat lookups from a mutex-guarded in-process cache, and retries only the status codes a second attempt can fix. This guide builds that wrapper - validate.rb, cache.rb and app.rb are new, and the Ruby quickstart's own seller_magnet.rb (the Client, ApiError and with_retry) is reused unchanged - and tests all of it with Minitest and Rack::Test against a fails-closed fake Net::HTTP layer, the same technique the mock-testing guide uses, so nothing here is just described.
Key Takeaways
- Validate asin and marketplace_id before the upstream call, so a bad request costs nothing and waits on no timeout.
- A TTLCache needs its own lock here: Sinatra under a threaded server (Puma with threads > 1, the usual production setup) runs several requests concurrently on the same process, so two lookups for the same ASIN can race on a bare Hash.
- 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 plain network error (a dropped connection, not an ApiError) is not an ApiError, so with_retry retries it the same way it retries a billed 502/503 - up to the attempt cap - but nothing was ever charged for it.
- seller_magnet.rb does not change between a thread-per-request Sinatra route and the quickstart's own Queue/Thread worker-pool script: the same Net::HTTP client fits both, one instance per thread.
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 Ruby quickstart's seller_magnet.rb on its own. This post reuses that file unchanged - its Client opens one keep-alive Net::HTTP connection and is not thread-safe by design, which is exactly why the Sinatra route below keeps one client per thread rather than sharing one.
Dependencies
gem install sinatra rack rack-protection
export SELLERMAGNET_API_KEY="your-key-here"
ruby app.rb -p 4567
How do I validate the ASIN and marketplace before spending a credit?
Put the shape checks in one method and call it before any network call. An ASIN is always 10 upper-case letters or digits; the marketplace ID must be one this wrapper actually supports (the full list of all 23 marketplace IDs is in the marketplace IDs list). A failing check raises a RequestValidationError before the route ever opens a connection, so a malformed request never waits on the 120-second timeout and never costs a credit. Two fields do not need a validation gem: a Regexp and a plain Hash are enough, and there is one fewer dependency to pin.
validate.rb - checked before any network call
ASIN_RE = /\A[A-Z0-9]{10}\z/
# The handful of marketplace IDs this wrapper covers; the full list of all 23
# is in https://sellermagnet-api.com/blog/amazon-marketplace-ids-list
MARKETPLACE_IDS = {
"ATVPDKIKX0DER" => true, # amazon.com
"A1PA6795UKMFR9" => true, # amazon.de
"A1F83G8C2ARO7P" => true, # amazon.co.uk
"A13V1IB3VIYZZH" => true, # amazon.fr
}.freeze
class RequestValidationError < StandardError
attr_reader :errors
def initialize(errors)
super("invalid lookup request")
@errors = errors
end
end
# Checked before any network call: a bad shape never opens a connection, so
# it never spends a credit and never waits on the 120 s timeout.
def validate_lookup_request(asin_raw, marketplace_id)
errors = []
asin = asin_raw.to_s.upcase
errors << { field: "asin", msg: "asin must be 10 upper-case letters/digits" } unless ASIN_RE.match?(asin)
unless MARKETPLACE_IDS[marketplace_id]
errors << { field: "marketplace_id", msg: "unknown marketplace_id: #{marketplace_id}" }
end
raise RequestValidationError, errors unless errors.empty?
[asin, marketplace_id]
end
How does the cache stay safe when several requests run at once?
TTLCache is a plain Hash keyed by asin:marketplace_id, with each entry carrying its own expiry, but every read and write goes through MonitorMixin#synchronize. Sinatra's own single-threaded WEBrick default only ever runs one request at a time against this process, the same no-lock-needed situation any synchronous, one-request-per-process worker model gives any server, but the realistic production setup - Puma, Sinatra's own recommended server, configured with threads 5, 5 or higher - calls the route from several threads on the SAME process at once, so two lookups for the same ASIN arriving together can race on a bare Hash without a lock. A lookup within the TTL (300 seconds here) returns the stored result with cached: true and makes no network call at all; this service also runs as one process, so running several Puma workers (not just threads) behind a load balancer still means each worker process keeps its own cache - the same single-process trade-off any synchronous, one-worker-per-process service has, not hidden here either.
cache.rb - a MonitorMixin-guarded in-process TTL cache
require "monitor"
# TTLCache is a tiny in-process cache, keyed by "asin:marketplaceId". Sinatra
# under a threaded server (Puma with threads > 1, the usual production
# setup) runs several requests concurrently on the SAME process, so - unlike
# a single synchronous worker process - this cache needs its own lock: two
# requests for the same ASIN can race on a bare Hash without one.
class TTLCache
include MonitorMixin
def initialize(ttl_seconds)
super()
@ttl = ttl_seconds
@store = {}
end
def get(key)
synchronize do
entry = @store[key]
return nil unless entry
if Time.now > entry[:expires_at]
@store.delete(key) # expired: evict so size reflects live entries only
return nil
end
entry[:value]
end
end
def set(key, value)
synchronize { @store[key] = { expires_at: Time.now + @ttl, value: value } }
end
def size
synchronize { @store.size }
end
end
What does the Sinatra route itself look like?
The route validates the path and query parameters first, checks the cache, and only then calls SellerMagnet.with_retry around the quickstart's own Client#lookup. Each thread keeps its own Client in Thread.current, because Net::HTTP connections are not thread-safe and must not be shared - the same rule the quickstart's own bulk.rb worker pool follows. A plain network error - a dropped connection, not an ApiError - does not stop with_retry early: it is retried up to the same attempt cap as a billed 502/503, the difference being that nothing was ever charged for it.
app.rb - the Sinatra microservice
require "sinatra/base"
require "json"
require_relative "seller_magnet"
require_relative "validate"
require_relative "cache"
# Validation (validate.rb) and the cache (cache.rb) are new; seller_magnet.rb
# above is the Ruby quickstart's own Client, ApiError and with_retry,
# unchanged - the Net::HTTP connection it opens per-thread is already safe
# for the way Sinatra calls into a route under a threaded server.
class AmazonLookupApp < Sinatra::Base
set :show_exceptions, false
set :cache, TTLCache.new(300) # 300 s TTL, shared by every thread in this process
set :host_authorization, { permitted_hosts: [] } # this app sits behind its own reverse proxy / LB, not open on the internet
get "/lookup/:asin" do
content_type :json
begin
asin, marketplace_id = validate_lookup_request(params[:asin], params["marketplace_id"].to_s)
rescue RequestValidationError => e
halt 422, { detail: e.errors }.to_json
end
cache_key = "#{asin}:#{marketplace_id}"
if (hit = settings.cache.get(cache_key))
halt 200, hit.merge(cached: true).to_json
end
client = Thread.current[:sm_client] ||= SellerMagnet::Client.new
begin
result = SellerMagnet.with_retry { client.lookup(asin, marketplace_id) }
rescue SellerMagnet::ApiError => e
halt 404, { detail: "asin not found on this marketplace" }.to_json if e.status == 404
halt 502, { detail: "upstream lookup failed" }.to_json
rescue *SellerMagnet::NETWORK_ERRORS
# Never reached the server at all, so nothing was billed - still a 502
# to the caller, same as a billed upstream 502/503 above.
halt 502, { detail: "upstream lookup failed" }.to_json
end
settings.cache.set(cache_key, result)
result.merge(cached: false).to_json
end
end
A client timeout is not the same as a free connection error
The connection-error branch above only ever fires when the request never reached the server at all (a dropped connection, a refused socket), so nothing was billed. A client timeout is different: the credit is deducted on the server before the scrape even starts, so a client that gives up waiting and cancels its own request has still paid for an answer it will never see, and that credit is not refunded (refunds only exist for a server-side 500). Keep read_timeout at 120 seconds, matching the quickstart's own Client#initialize, rather than cutting it short to "fail fast".

Trimmed response for a cache-miss lookup
{
"asin": "B0CL61F39H",
"title": "PlayStation\u00ae5 console (slim)",
"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 marketplace_id | 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 error (never reached the server) | 502 | yes, up to 4 attempts | No - nothing was billed |

test_app.rb - 14 scenarios against a fails-closed fake Net::HTTP, run with Minitest + Rack::Test
require "minitest/autorun"
require "rack/test"
require "json"
require_relative "fake_transport"
require_relative "app"
# Stub Kernel#sleep for the whole suite: with_retry's own exponential
# backoff still runs and is still exercised below, it just does not really
# wait. Production code is never affected: only the test process loads this.
module SleepStub
def sleep(_seconds)
0
end
end
Object.prepend(SleepStub)
ENV["SELLERMAGNET_API_KEY"] ||= "test-key"
ASIN = "B0CL61F39H"
MARKET = "ATVPDKIKX0DER"
def ok(data)
FakeResponse.new(code: 200, body: JSON.generate({ "success" => true, "data" => data }))
end
def fail_response(status, message, headers: {})
FakeResponse.new(code: status, body: JSON.generate({ "success" => false, "message" => message }), headers: headers)
end
def product(price)
{ "productInfo" => { "asin" => ASIN, "title" => "PlayStation5 console (slim)",
"buyBoxInfo" => { "price" => price, "currencyCode" => "USD" },
"link" => "https://www.amazon.com/dp/#{ASIN}" } }
end
class AppTest < Minitest::Test
include Rack::Test::Methods
def app
AmazonLookupApp.new
end
def setup
FakeTransport.reset
app.settings.cache.instance_variable_set(:@store, {}) # fresh cache per test
end
def teardown
FakeTransport.reset
end
def lookup(asin, marketplace_id)
get "/lookup/#{asin}", marketplace_id: marketplace_id
end
def test_valid_lookup_returns_price_and_is_not_cached
FakeTransport.install(->(_req) { ok(product(444.99)) })
lookup(ASIN, MARKET)
assert_equal 200, last_response.status
body = JSON.parse(last_response.body)
refute body["cached"]
assert_equal 444.99, body["price"]
assert_equal "USD", body["currency"]
assert_equal 1, FakeTransport.calls.size
end
def test_second_lookup_is_served_from_cache_without_a_second_call
FakeTransport.install(->(_req) { ok(product(444.99)) })
lookup(ASIN, MARKET)
lookup(ASIN, MARKET)
assert_equal 200, last_response.status
assert JSON.parse(last_response.body)["cached"]
assert_equal 1, FakeTransport.calls.size # the second hit never reached the network
end
def test_malformed_asin_is_rejected_before_422_and_no_network_call
lookup("not-an-asin", MARKET)
assert_equal 422, last_response.status
assert_equal 0, FakeTransport.calls.size
end
def test_unknown_marketplace_is_rejected_before_422_and_no_network_call
lookup(ASIN, "ZZZUNKNOWNID")
assert_equal 422, last_response.status
assert_equal 0, FakeTransport.calls.size
end
def test_lowercase_asin_is_normalized_then_looked_up
FakeTransport.install(->(_req) { ok(product(444.99)) })
lookup(ASIN.downcase, MARKET)
assert_equal 200, last_response.status
assert_equal ASIN, JSON.parse(last_response.body)["asin"]
end
def test_upstream_404_is_billed_and_never_retried
FakeTransport.install(->(_req) { fail_response(404, "not found") })
lookup(ASIN, MARKET)
assert_equal 404, last_response.status
assert_equal 1, FakeTransport.calls.size
end
def test_upstream_429_is_free_and_retried_until_it_succeeds
attempt = 0
FakeTransport.install(lambda do |_req|
attempt += 1
attempt == 1 ? fail_response(429, "concurrency cap", headers: { "Retry-After" => "2" }) : ok(product(10.0))
end)
lookup(ASIN, MARKET)
assert_equal 200, last_response.status
assert_equal 2, FakeTransport.calls.size
end
def test_upstream_500_is_refunded_and_retried_exactly_once
attempt = 0
FakeTransport.install(lambda do |_req|
attempt += 1
attempt == 1 ? fail_response(500, "internal") : ok(product(10.0))
end)
lookup(ASIN, MARKET)
assert_equal 200, last_response.status
assert_equal 2, FakeTransport.calls.size
end
def test_two_consecutive_500s_stop_instead_of_looping_forever
FakeTransport.install(->(_req) { fail_response(500, "internal") })
lookup(ASIN, MARKET)
assert_equal 502, last_response.status
assert_equal 2, FakeTransport.calls.size # retried once (refunded), then stopped
end
def test_upstream_502_is_billed_on_every_attempt_up_to_the_cap
FakeTransport.install(->(_req) { fail_response(502, "bad gateway") })
lookup(ASIN, MARKET)
assert_equal 502, last_response.status
assert_equal 4, FakeTransport.calls.size # with_retry attempts: 4
end
def test_upstream_503_stays_capped_at_four_attempts_never_a_fifth
FakeTransport.install(->(_req) { fail_response(503, "unavailable") })
lookup(ASIN, MARKET)
assert_equal 502, last_response.status
assert_equal 4, FakeTransport.calls.size
end
def test_connection_error_is_never_billed_and_surfaces_as_502
FakeTransport.install(->(_req) { raise Errno::ECONNRESET })
lookup(ASIN, MARKET)
assert_equal 502, last_response.status
assert_equal 4, FakeTransport.calls.size # retried up to the same cap, nothing was ever charged
end
def test_fake_transport_fails_closed_without_install
assert_raises(RuntimeError) do
SellerMagnet::Client.new.lookup(ASIN, MARKET)
end
end
def test_concurrent_lookups_of_the_same_asin_share_one_cache_safely
calls = 0
mutex = Mutex.new
FakeTransport.install(lambda do |_req|
mutex.synchronize { calls += 1 }
ok(product(444.99))
end)
shared_app = AmazonLookupApp.new
threads = Array.new(8) do
Thread.new do
session = Rack::Test::Session.new(Rack::MockSession.new(shared_app))
session.get("/lookup/#{ASIN}", marketplace_id: MARKET)
session.last_response.status
end
end
statuses = threads.map(&:value)
assert statuses.all? { |s| s == 200 }
assert_operator FakeTransport.calls.size, :>=, 1 # no crash, no partial writes under concurrent access
end
end
Real output: ruby test_app.rb --verbose (unmodified run)
Run options: --verbose --seed 6009
# Running:
AppTest#test_connection_error_is_never_billed_and_surfaces_as_502 = 0.04 s = .
AppTest#test_lowercase_asin_is_normalized_then_looked_up = 0.00 s = .
AppTest#test_second_lookup_is_served_from_cache_without_a_second_call = 0.00 s = .
AppTest#test_unknown_marketplace_is_rejected_before_422_and_no_network_call = 0.00 s = .
AppTest#test_valid_lookup_returns_price_and_is_not_cached = 0.00 s = .
AppTest#test_malformed_asin_is_rejected_before_422_and_no_network_call = 0.00 s = .
AppTest#test_fake_transport_fails_closed_without_install = 0.00 s = .
AppTest#test_upstream_500_is_refunded_and_retried_exactly_once = 0.00 s = .
AppTest#test_concurrent_lookups_of_the_same_asin_share_one_cache_safely = 0.06 s = .
AppTest#test_upstream_429_is_free_and_retried_until_it_succeeds = 0.00 s = .
AppTest#test_upstream_404_is_billed_and_never_retried = 0.00 s = .
AppTest#test_upstream_503_stays_capped_at_four_attempts_never_a_fifth = 0.01 s = .
AppTest#test_two_consecutive_500s_stop_instead_of_looping_forever = 0.00 s = .
AppTest#test_upstream_502_is_billed_on_every_attempt_up_to_the_cap = 0.00 s = .
Finished in 0.134495s, 104.0933 runs/s, 230.4923 assertions/s.
14 runs, 31 assertions, 0 failures, 0 errors, 0 skips
This cache is per process, and so is the test suite's fake transport
Running the service as several Puma workers behind a load balancer means each one holds its own cache, so the same ASIN can still be fetched once per worker within the TTL. That is a reasonable default for a single small service; a reader running several workers should size the TTL around that, or swap in a shared store of their own choice - this post does not name one.
Frequently Asked Questions
Why validate with a Regexp and a Hash instead of a validation gem?
Either works. For two fields - an ASIN regex and a marketplace membership check - a small method avoids an extra dependency; a larger request shape is a better fit for a schema-based validation gem.
Does the cache in this wrapper work across multiple Puma workers?
No. TTLCache is a plain in-process Hash guarded by its own lock; each worker process keeps its own copy. Several workers sharing one cache need an external store, 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 never retried.
Why does a connection error still get retried up to the attempt cap?
with_retry retries any error it sees unless it can prove (via ApiError) that retrying is pointless; a plain network error is not an ApiError, so it gets the same attempt cap as a billed 502/503 - the difference is that a connection error was never charged.
Why does the cache need a lock here but might not in a synchronous single-process setup?
A synchronous, one-request-per-process worker model never has two requests running against the same process at once, so a plain in-process cache dict is safe there without any lock. Sinatra under Puma with multiple threads calls the route from several threads on the same process at once, so concurrent requests for the same key can race on a bare Hash without a lock.
Bottom line: validate before any network call, cache repeat lookups for free in a mutex-guarded in-process TTLCache, and reuse the quickstart's own client and retry policy unchanged. Every behaviour here came from running Minitest and Rack::Test against real code with only Net::HTTP#request faked - see the Ruby quickstart for the client's own retry details, the mock-testing guide for the fake-transport technique, and the API documentation for every endpoint.