Skip to content

Add c-ares support for DNS resolution with timeout#323

Open
bjosv wants to merge 3 commits into
valkey-io:mainfrom
bjosv:use-cares
Open

Add c-ares support for DNS resolution with timeout#323
bjosv wants to merge 3 commits into
valkey-io:mainfrom
bjosv:use-cares

Conversation

@bjosv

@bjosv bjosv commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator

getaddrinfo() has no timeout mechanism. When DNS is slow or unresponsive, libvalkey hangs indefinitely with no way to cancel the lookup.

This PR adds optional c-ares integration (USE_CARES=1 / -DENABLE_CARES=ON) that replaces getaddrinfo() with c-ares driven by a poll() loop. DNS resolution respects connect_timeout (defaulting to 5 seconds if unset), so lookups that previously hung indefinitely now fail with a timeout error.

The PR consists of two commits: the first moves existing DNS logic into dns.[ch], and the second adds the c-ares integration.

Notes:

  • The async API currently still blocks during DNS (now with a timeout). A follow-up PR
    Add non-blocking DNS for the async API via c-ares event-loop integration #324
    will make DNS fully non-blocking for the async API via event-loop integration.
  • Without c-ares enabled, behavior is unchanged (plain getaddrinfo)
  • IPv4/IPv6 preference flags and fallback behavior are preserved
  • IPv6 literals (e.g. ::1) are detected and handled correctly
  • Targets Linux, macOS, FreeBSD (not Windows)

Testing:

  • New ut_dns_cares unit test covering IP literals, hostnames, non-existent hosts, IPv6, and timeout
  • OOM handling test updated to accommodate additional allocations from c-ares
  • ut_connect_fallback disabled when c-ares is enabled (it overrides getaddrinfo which c-ares bypasses)
  • New CI job with sanitizers and IPv6 tests enabled

bjosv added 3 commits June 22, 2026 14:40
Signed-off-by: Björn Svensson <bjorn.a.svensson@est.tech>
When built with USE_CARES=1 (make) or -DENABLE_CARES=ON (CMake),
DNS resolution in the sync API uses c-ares with a poll loop bounded
by connect_timeout (defaulting to 5s). This prevents indefinite hangs
when DNS is slow or unresponsive.

The c-ares path uses ARES_OPT_SOCK_STATE_CB for fd tracking, and a
short-lived channel per resolve call. IPv4/IPv6 fallback behavior is
preserved.

Without enabling c-ares, behavior is unchanged (plain getaddrinfo).

Signed-off-by: Björn Svensson <bjorn.a.svensson@est.tech>
Signed-off-by: Björn Svensson <bjorn.a.svensson@est.tech>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant