> ## Content Index
> Fetch the complete content index at: https://stalin-pereira.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Dependencies That Hang Are Worse Than Dependencies That Fail
- URL: https://stalin-pereira.com/dependencies-that-hang-are-worse-than-dependencies-that-fail/
- Published: 2026-11-04T08:30:00.000Z
- Updated: 2026-11-04T08:30:00.000Z
- Description: A queue that silently hung on a misconfigured Redis connection, a dashboard one dead host could freeze, and the fix for both: deadlines, serve-first startup and visible health.
- Author: Stalin Pereira
- Tags: Backend

An error is a gift. It tells you something broke, roughly where, and usually why. A dependency that *hangs* gives you none of that. The request just sits there, the log stays quiet, and every check you can think of says the thing is healthy.

I ran into this twice with Redis in two different projects, once as a bug hunt and once as a design problem. Both came down to the same lesson: a call that can wait forever eventually will, so give every external call a deadline and make the result visible.

## Part 1: the queue that never said no

The setup was ordinary. An API endpoint takes a batch of work, pushes a job onto a BullMQ queue, and returns. A worker picks the job up later. In production, the endpoint simply never answered. No error, no timeout, no log line after "adding job". The HTTP client eventually gave up on its own.

My first guess was the network, so I checked it from every side I could:

- `redis-cli` from the same environment connected and got `PONG`.
- A raw ioredis client, built from the same connection string, connected and ran commands.
- Only `queue.add()` hung.

That was the useful part. When the lower layers work and a higher one doesn't, the problem isn't "Redis is down". It's whatever sits between those layers. So I stopped poking at the network and went layer by layer: the raw client works, the queue built on top of it doesn't, so the difference is in how the queue gets its connection.

And there it was. The config passed the Redis URL string straight through as the queue's `connection` option:

```javascript
// What I had: a URL string where an options object was expected
const queue = new Queue('jobs', {
  connection: redisUrl,
});
```

BullMQ documents `connection` as ioredis options or an existing ioredis instance. A string isn't either. Nothing validated it, nothing threw, and the client never got to a state where it would run a command, so the command waited, and kept waiting. A thin framework wrapper sat in between and passed the value through untouched, which is why it looked plausible in the config.

The fix was small. Parse the URL into the shape the library expects:

```javascript
function toRedisOptions(url) {
  const u = new URL(url);
  return {
    host: u.hostname,
    port: Number(u.port) || <default-port>,
    // plus the auth fields and db index from the URL, decoded, if present
  };
}

const queue = new Queue('jobs', { connection: toRedisOptions(redisUrl) });
```

The more lasting change was what I added while hunting: a small health endpoint that opens its own short-lived Redis client with a hard timeout and reports whether it got a reply and how long it took. I first added it as a diagnostic, then kept it. The next time something smells like Redis, I'll find out in one request instead of an evening.

```javascript
async function redisPing() {
  const client = new Redis({
    host: '<redis-host>', port: <port>,
    lazyConnect: true,
    connectTimeout: <ms>,
    maxRetriesPerRequest: 1,
    enableOfflineQueue: false,   // fail instead of waiting
  });
  const start = Date.now();
  try {
    await client.connect();
    return { ok: true, reply: await client.ping(), ms: Date.now() - start };
  } catch (err) {
    return { ok: false, error: err.message, ms: Date.now() - start };
  } finally {
    client.disconnect();
  }
}
```

## Part 2: one dead dependency shouldn't take everything down

The second time was a small dashboard that watches several Redis-backed queues at once. Each Redis is its own configured connection. One of them pointed at a host that had gone away, and the whole dashboard stopped loading. Not just that board: everything.

Startup looked like this: for each connection, connect, discover its queues, register them, then move on to the next one. Only after the loop finished did the HTTP server start listening. One unreachable host meant the loop never finished, so the server never listened.

Why didn't it fail? Because ioredis, by default, has an **offline queue**. When the client isn't connected, commands aren't rejected. They're held until the connection comes up. That's a good default for a brief blip, and a terrible one for a host that's gone for good. Combined with retries that never give up, "discover the queues on this connection" becomes a promise that never settles.

#### Connect, then serve

1. Connect A, discover queues ok
2. Connect B, discover queues waiting forever
3. Connect C never reached
4. Start HTTP server never reached

Result: nothing loads, nothing logs.

#### Serve, then connect

1. Start HTTP server listening
2. A, B, C sync in the background, each with a deadline
3. A ok B error: no reply in time C ok
4. B keeps retrying on its refresh timer

Result: two boards work, one shows why it doesn't.

The same unreachable dependency, two startup orders. Only one of them turns a hang into a visible error.

The fix had a few parts, and each one is a reusable rule.

**Serve first, connect in the background.** Create everything that doesn't need the network (routes, empty boards, status entries) up front, start listening, then kick off each connection without awaiting it in the startup path. A dependency being down is now a state the app is in, not a reason it fails to exist.

**Put a deadline on the wait.** I wrap "wait until the client is ready" and "discover the queues" in a timeout. Waiting for readiness listens for the client's ready event instead of sending a command, so nothing piles up in the offline queue while we wait.

```javascript
function withTimeout(promise, ms, message) {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error(message)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
```

Where you'd rather have commands fail fast than wait, turn the offline queue off (`enableOfflineQueue: false`) and cap retries per request. Keep it on where riding out a short reconnect matters more than a quick answer. It's a choice. Just don't leave it to the default by accident.

**Isolate each component.** Each queue gets registered in its own `try/catch`. One bad queue name used to throw during startup and crash the process. Now it's logged and shown on that connection's card, and everything else carries on.

**Ignore results that arrive too late.** A background sync can outlive its connection. If someone edits or deletes a connection while a sync is still waiting, the old sync must not write its result over the new one. I keep a generation counter per connection, bump it on teardown, and have the sync check it before applying anything. If it changed, the result is thrown away.

**Don't let retries pile up.** The refresh timer starts before the first sync, so a connection that's down at boot keeps retrying. It skips a tick while a sync is still in flight, so a slow host doesn't collect a stack of waiting attempts.

Two Redis-specific traps showed up along the way too. In cluster mode, scanning "the server" only scans one shard, so discovery has to go through every master node. And with TLS against a managed cluster, the hostnames you connect to must match what the provider advertises on its certificates, or the handshake fails in ways that look a lot like a hang.

## Trade-offs

Serving before your dependencies are ready means your app has to handle "not ready yet" as a real state: in the UI, in health checks, in requests that need that dependency. That's more code than a startup that simply refuses to run. If your service is useless without its one database, failing fast at boot is fine, as long as it *fails* and doesn't wait forever. Timeouts also need choosing: too short and a slow but healthy dependency looks broken, too long and you're back to a hang with extra steps.

## Takeaway

A dependency that fails is easy to handle. One that hangs quietly stalls everything that waits on it. Give every external call a deadline, start up without waiting on things you can't control, and make each dependency's health something you can see in one request.