Skip to content

Perf: header merge allocates a fresh 4-way dict per retry attempt #262

Closed

Description

@TexasCoding

Summary

On every request and every retry attempt, four dicts are merged into a new dict literal. Only auth_headers actually changes between attempts (fresh timestamp); the other three are loop-invariant. Per request the surplus is ~3 dict copies — small per call but allocated in the per-request hot path used by every resource method.

Location

  • kalshi/_base_client.py:213-225 — sync
  • kalshi/_base_client.py:391-405 — async

Evidence

config_extra = self._config.extra_headers or {}
per_call_extra = extra_headers or {}
body_headers = headers or {}

for attempt in range(self._config.max_retries + 1):
    auth_headers = self._auth.sign_request(method.upper(), sign_path) if self._auth else {}
    merged_headers = {
        **config_extra,
        **per_call_extra,
        **body_headers,
        **auth_headers,
    }

Recommended fix

Build base = {**config_extra, **per_call_extra, **body_headers} once before the retry loop, then merged = {**base, **auth_headers} per attempt — saves N-1 merges over retries and is also clearer about which layer changes.

Severity & category

medium / performance

Activity

  1. added a commit that references this issue on May 21, 2026
    72dba04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance / hot-path concern

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions