All posts

Fix Load Balancer Error in Haskell

Resolve Haskell web application issues behind load balancers, covering Warp configuration, proxy headers, and connection handling.

Haskell Web Apps Behind Load Balancers

Haskell web frameworks like Servant and Yesod run on Warp under the hood. When placed behind a load balancer, you need to handle proxy headers and connection management properly.

Warp Proxy Configuration

Warp needs to trust forwarded headers from your load balancer:

import Network.Wai.Handler.Warp
import Network.Wai.Middleware.RequestLogger
import Network.Wai.Middleware.ForceSSL

main :: IO ()
main = do
  let settings = setPort 8080
                $ setHost "0.0.0.0"
                $ setTimeout 120
                $ defaultSettings
  runSettings settings app

For SSL detection behind a proxy, check X-Forwarded-Proto:

import Network.Wai

isSecure :: Request -> Bool
isSecure req =
  case lookup "X-Forwarded-Proto" (requestHeaders req) of
    Just "https" -> True
    _            -> False

Health Check Endpoint

With Servant:

type HealthAPI = "healthz" :> Get '[PlainText] Text

healthHandler :: Handler Text
healthHandler = return "ok"

Connection Draining

Haskell's lightweight threads mean Warp can handle thousands of connections, but graceful shutdown requires explicit handling:

import Control.Concurrent (threadDelay)
import System.Posix.Signals

main = do
  installHandler sigTERM (Catch $ gracefulShutdown) Nothing
  runSettings settings app

gracefulShutdown :: IO ()
gracefulShutdown = do
  putStrLn "Shutting down gracefully..."
  threadDelay 5000000 -- 5 seconds for in-flight requests

Bugsly can receive error reports from Haskell backends via its HTTP API, capturing exceptions that might otherwise vanish in container restarts behind the balancer.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free