Skip to content

RSA-PSS / MGF1 / SHA256 config allocated per signature instead of module-level constants #345

Closed

Description

@TexasCoding

Problem

Every call to KalshiAuth.sign_request constructs four stateless cryptography configuration objects: a fresh hashes.SHA256() inside MGF1, a fresh padding.MGF1(...), a fresh padding.PSS(...), and a second hashes.SHA256() passed as the algorithm parameter. These are pure immutable algorithm descriptors — a well-known idiom is to hoist them to module-level constants for high-RPS code.

The per-call cost is small (~Python-object allocation + GC churn) versus the ~1–3 ms RSA-PSS sign, but it is paid on every REST request and every WS reconnect, and scripts/bench_request_hot_path.py is set up to measure exactly that kind of SDK overhead.

Evidence

  • kalshi/auth.py:279-286:
signature = self._private_key.sign(
    message_bytes,
    padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.DIGEST_LENGTH,
    ),
    hashes.SHA256(),
)
  • scripts/bench_request_hot_path.py — existing bench harness already targets the REST hot path the change would improve.

Suggested fix

Define module-level constants in kalshi/auth.py:

_SHA256 = hashes.SHA256()
_PSS_PADDING = padding.PSS(
    mgf=padding.MGF1(_SHA256),
    salt_length=padding.PSS.DIGEST_LENGTH,
)

Then:

signature = self._private_key.sign(message_bytes, _PSS_PADDING, _SHA256)

The cryptography library treats PSS/MGF1/SHA256 instances as configuration values and explicitly supports reuse across operations. Extend scripts/bench_sign_offload.py (or bench_request_hot_path.py) to lock in the per-sign throughput delta.

Source

Round-3 independent audit (reviewer: performance).

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 concernpolishCode-quality and DX improvements; non-functional

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions