Here is a production bug you can reproduce in four lines of Crystal:

1
2
3
4
5
require "http/client"

response = HTTP::Client.get("https://api.example.com/v1/items")
puts response.status_code   # 301
puts response.body          # "" — and nobody noticed

Crystal’s standard library HTTP client does not follow redirects and does not raise on a 500. It returns a response object and lets you decide what it means. That is a defensible design for a language runtime, and a genuinely dangerous default for application code: a misconfigured base URL turns into an empty list instead of an exception, and your monitoring stays green while the feature is silently dead.

The three options in this comparison differ mainly in how much of that responsibility they take off your hands. Quick verdict: reach for Crest for application HTTP calls that touch third-party services, use the stdlib HTTP::Client for internal, well-understood endpoints or when you cannot add dependencies, and consider Halite only if you specifically need its middleware and session model — it has not been released since 2022.

The Three Contenders at a Glance

Criterionstdlib HTTP::ClientCrestHalite
VersionShips with Crystal1.9.00.12.1
GitHub starsCrystal itself: 20,530249171
Last commitDec 2026 (language)Nov 2026Mar 2022
LicenseApache-2.0 (Crystal)MITMIT
External shard dependenciesNone3 (cookie_jar, http_proxy, digest auth)None
Follows redirectsNoYes, 10 by default, with response.historyYes, configurable
Raises on 4xx/5xxNoYes by default (Crest::RequestFailed)Yes (Halite::ClientError / ServerError)
Query params helperManualYes (params:)Yes (params:)
JSON request helperManualYes (json: true)Yes (json:)
Multipart uploadsManualYesYes
Cookie jar / sessionsManualCookie jar supportBuilt-in session object
Middleware hooksNoneLogging, custom clientsFeature registration and interception
Default timeoutsNoneNone unless specifiedNone unless specified

Two of these three ship no timeout by default, and that is the single most common way a Crystal service hangs in production. We will come back to it.

Decision Matrix: Ten Seconds to a Choice

Your situationPickWhy
Calling Stripe, GitHub, or any third-party REST APICrestRedirect following, error raising, JSON helpers, timeouts in one call
Internal service call with a known-good URLstdlibZero dependencies, zero abstraction, predictable
Long-lived client with cookies and login flowHaliteSession object with persistent state
You need request interception for tracingHalite or CrestHalite has explicit features; Crest exposes logging and custom clients
Shipping a static binary in a minimal containerstdlib or HaliteCrest pulls three extra shards
Codebase that must stay on a maintained dependencyCrestOnly actively developed option of the two shards
Downloading large files with progressCrest or stdlib streamingBoth support streaming bodies; Halite is stale

stdlib HTTP::Client — Small, Fast, and Entirely Your Problem

The standard library client is a thin wrapper over sockets. You construct a client, reuse it, and close it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
require "http/client"
require "json"

client = HTTP::Client.new("api.example.com", tls: true)

response = client.get(
  "/v1/items?limit=50",
  headers: HTTP::Headers{"Authorization" => "Bearer #{ENV["API_TOKEN"]}"}
)

case response.status_code
when 200
  items = JSON.parse(response.body)["items"].as_a
when 401
  raise "token rejected"
else
  raise "unexpected status #{response.status_code}: #{response.body[0, 200]}"
end

client.close

A POST with a JSON body is still manual, but not painful:

1
2
3
4
5
6
7
payload = {"name" => "widget", "qty" => 3}.to_json

response = client.post(
  "/v1/items",
  headers: HTTP::Headers{"Content-Type" => "application/json"},
  body: payload
)

The performance story is the good part. HTTP::Client keeps the connection open between requests, so a loop of 100 calls on one client instance negotiates TLS once. Constructing a new client per request throws that away and adds a full handshake to every call — a difference you can measure in tens of milliseconds per request against a remote host.

The correctness story is the bad part. Everything the stdlib does not do is now your job:

1
2
3
4
5
6
# Redirects: you must handle them yourself
response = HTTP::Client.get("http://example.com/old-path")
if response.status_code.redirect?
  location = response.headers["Location"]
  response = HTTP::Client.get(location)
end

That snippet is already wrong for 307 and 308 (method must be preserved) and for relative Location headers. This is the exact category of code that Crest exists to delete from your application.

Crest — The Pragmatic Application Client

Crest wraps the stdlib client with the behaviors application code expects: redirect following, exception raising on HTTP errors, query parameter encoding, JSON requests, multipart uploads, proxies, cookie jars, and per-request timeouts.

1
2
3
4
5
# shard.yml
dependencies:
  crest:
    github: mamantoha/crest
    version: ~> 1.9.0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
require "crest"

response = Crest.get(
  "https://api.example.com/v1/items",
  params: {:limit => 50},
  headers: {"Authorization" => "Bearer #{ENV["API_TOKEN"]}"},
  connect_timeout: 2.seconds,
  read_timeout: 10.seconds
)

response.status_code   # 200
response.body          # raw body

A JSON POST collapses to one call:

1
2
3
4
5
6
response = Crest.post(
  "https://api.example.com/v1/items",
  {:name => "widget", :qty => 3},
  json: true,
  read_timeout: 10.seconds
)

Error handling is the reason most teams adopt it. With the default handle_errors: true, any 4xx or 5xx raises Crest::RequestFailed, which carries the response:

1
2
3
4
5
6
begin
  Crest.get("https://api.example.com/v1/items", read_timeout: 5.seconds)
rescue ex : Crest::RequestFailed
  Log.warn(exception: ex) { "upstream failed with #{ex.response.status_code}" }
  raise ex
end

Set handle_errors: false when a 404 is a normal branch rather than a failure, and Crest returns the response instead of raising. Redirects are followed up to max_redirects (default 10), and response.history gives you the chain of responses — useful when a partner API starts bouncing you through a login flow.

Multipart uploads and streaming downloads are supported directly:

1
2
3
4
5
6
7
8
9
Crest.post(
  "https://api.example.com/v1/files",
  {"file" => File.open("report.pdf"), "name" => "report"},
  read_timeout: 60.seconds
)

Crest.get("https://api.example.com/v1/export.csv") do |response|
  File.open("export.csv", "w") { |f| IO.copy(response.body_io, f) }
end

The tradeoff is dependency surface: Crest pulls in cookie_jar, http_proxy, and http-client-digest_auth. For a static binary in a scratch container, that is three more shards to compile — not a problem, but not nothing.

Halite — Sessions, Middleware, and a Maintenance Question

Halite models itself on Python’s requests. It has a chainable API, a built-in session, response MIME adapters, and a feature-registration system that acts as middleware.

1
2
3
4
5
# shard.yml
dependencies:
  halite:
    github: icyleaf/halite
    version: ~> 0.12.1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
require "halite"

# Chainable request
response = Halite.header(private_token: "T0k3n")
                 .get("https://api.example.com/v1/items", params: {language: "crystal"})

# JSON body
response = Halite.post(
  "https://api.example.com/v1/items",
  json: {"name" => "widget"},
  timeout: {connect: 2.seconds, read: 10.seconds}
)

The session object is the feature that distinguishes it. Cookies and headers persist across requests when you configure them through Halite::Options, which makes login-then-scrape flows shorter than the equivalent stdlib code:

1
2
3
4
5
6
options = Halite::Options.new
options.headers["Authorization"] = "Bearer #{token}"

session = Halite::Session.new(options)
session.get("https://api.example.com/v1/me")
session.get("https://api.example.com/v1/orders")

The middleware system registers named features that can inspect and mutate requests and responses — the documented example registers a feature that rewrites a 404 into something else. If you have ever wanted a request-level tracing hook in Crystal without forking a client, this is the closest thing available.

The problem is time. Halite’s newest release, 0.12.1, dates to 2022, and the repository’s last commit was March 2022. It declares support for Crystal >= 0.36.1, < 2.0.0, which is a broad range, but a four-year gap in a networking library is a real risk: TLS behavior, cookie handling, and stdlib HTTP internals have all changed since then. Choose it for the session and middleware model, not because it is the safer default.

Timeouts, Concurrency, and Connection Reuse

Crystal’s concurrency model makes it easy to fire many requests at once, and easy to leak connections while doing it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
require "crest"

channel = Channel(Tuple(Int32, String)).new

urls.each do |url|
  spawn do
    begin
      response = Crest.get(url, connect_timeout: 2.seconds, read_timeout: 5.seconds)
      channel.send({response.status_code, url})
    rescue ex
      channel.send({0, "#{url}: #{ex.message}"})
    end
  end
end

urls.size.times { puts channel.receive }

Three rules keep this from turning into an outage:

  1. Always set both connect_timeout and read_timeout. Crest, Halite, and the stdlib all default to no timeout. A peer that accepts the TCP connection and then never responds will hold the fiber forever.
  2. Bound the concurrency. Spawning 5,000 fibers each opening a socket will exhaust file descriptors long before it exhausts the CPU. Use a worker pool or a semaphore.
  3. Reuse clients for sequential work. One HTTP::Client instance per sequential batch, not one per request, or you pay a TLS handshake every time.

If you want numbers for your own workload rather than someone else’s blog, measure it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
require "http/client"
require "benchmark"

Benchmark.ips do |x|
  x.report("reused client") do
    client = HTTP::Client.new("httpbin.org", tls: true)
    client.get("/get")
    client.close
  end
end

Run that against your actual endpoint, from your actual network. Published microbenchmarks rarely survive contact with a real TLS terminator and a real CDN.

Deployment: Static Binaries and Health Checks

Crystal compiles to a single binary, which makes container images pleasantly small. A multi-stage build with shards cached separately:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
FROM crystallang/crystal:latest-alpine AS build
WORKDIR /app
COPY shard.yml shard.lock ./
RUN shards install --production
COPY . .
RUN shards build --release --static

FROM alpine:3.20
RUN apk add --no-cache ca-certificates tzdata
COPY --from=build /app/bin/worker /usr/local/bin/worker
USER 10001
ENTRYPOINT ["/usr/local/bin/worker"]

The ca-certificates line is not optional. A static Crystal binary in a bare Alpine image will fail every HTTPS request with a certificate verification error, which looks like a network problem and is actually a missing trust store.

For health checks, probe the dependency rather than the process:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# docker-compose.yml (excerpt)
services:
  worker:
    image: registry.example.com/crystal-worker:2026.12
    environment:
      API_TOKEN: ${API_TOKEN}
      UPSTREAM_URL: https://api.example.com
    healthcheck:
      test: ["CMD", "/usr/local/bin/worker", "healthcheck"]
      interval: 30s
      timeout: 5s
      retries: 3

A healthcheck subcommand that performs one real request with a 2-second connect timeout tells you whether the upstream is reachable. A TCP check tells you the container is running, which you already knew.

Pitfalls That Cost Real Debugging Time

  1. No default timeouts anywhere. Not in the stdlib, not in Crest, not in Halite. Set them explicitly on every call path.
  2. The stdlib ignores redirects. A 301 returns an empty body and a status code you probably are not checking.
  3. HTTP::Client instances are not meant to be shared across fibers for concurrent requests. Use one client per fiber, or serialize access.
  4. Relative Location headers break naive redirect handling. Let Crest do it.
  5. Missing ca-certificates in slim images produces SSL_connect: certificate verify failed, which reads like a TLS bug and is a packaging bug.
  6. Halite’s age. If you adopt it, pin the version, and be prepared to vendor a patch if a future Crystal release changes stdlib HTTP semantics.
  7. Response body size. response.body reads everything into memory. For exports and large JSON payloads, stream with body_io.

Where This Fits in a Crystal Service

HTTP client choice looks trivial until you have ten integrations. At that point the difference between “raises on 500” and “returns a response you forgot to check” is the difference between an alert and a silent data gap. Crest’s defaults are the ones you want for anything external; the stdlib is the right tool when the call is internal, simple, and fully under your control.

Related reading: our Crystal web frameworks comparison covers the server side of the same stack, the Crystal database libraries guide shows how to persist what your client fetches, and the Crystal testing frameworks comparison explains how to stub these HTTP calls in specs instead of hitting a live API.

Crest HTTP client logo

FAQ

Does Crystal’s stdlib HTTP client follow redirects automatically?

No. HTTP::Client.get returns the 3xx response as-is, including an empty body. You must read the Location header and issue a follow-up request yourself, taking care to preserve the method for 307 and 308 and to resolve relative locations. Crest handles all of this by default with max_redirects set to 10.

Does HTTP::Client raise an exception on a 500 response?

No. The stdlib client returns a response object for every HTTP status, including 4xx and 5xx. You are responsible for checking status_code. Crest raises Crest::RequestFailed by default and includes the response; set handle_errors: false when an error status is an expected branch.

Is Halite still maintained in 2026?

The newest release is 0.12.1 from 2022, and the repository’s last commit was in March 2022. It still compiles against current Crystal versions in most setups, but it is not actively developed. Use it only if you specifically need its session object or middleware features, and pin the version.

How do I set a timeout in Crystal HTTP clients?

Pass them explicitly. With Crest use connect_timeout: and read_timeout: (for example 2.seconds and 10.seconds). Halite accepts a timeout: {connect: 2.seconds, read: 10.seconds} hash. With the stdlib, set client.read_timeout = 10.seconds and client.connect_timeout = 2.seconds on the client instance. None of the three sets a default.

Which client should I use for many concurrent requests?

Use Crest or the stdlib with one client per fiber and a bounded worker pool. Do not share a single HTTP::Client across fibers issuing concurrent requests, and always bound concurrency so you do not exhaust file descriptors. Cache and reuse clients for sequential batches to avoid repeated TLS handshakes.

Why do HTTPS requests fail in my minimal Docker image?

Almost always a missing trust store. Install ca-certificates in the runtime image. Crystal binaries compiled with --static do not bundle a CA bundle, so certificate verification fails even though DNS and routing are fine.


💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com