Skip to content

Perf: snapshot apply walks the level list twice (validate tuples, then rebuild dict) #263

Closed

Description

@TexasCoding

Summary

OrderbookSnapshotMessage.model_validate already builds a list[tuple[Decimal, Decimal]] (one allocation per level); dict(msg.msg.yes) then re-iterates that list to build a dict (a second per-level Python-level walk). For a 200-level book that's 400 redundant tuple unpacks per snapshot. Snapshots are infrequent vs deltas so this is medium, not high.

Location

  • kalshi/ws/orderbook.py:108-112 — _apply_snapshot_inplace
  • kalshi/ws/models/orderbook_delta.py:21-30 — snapshot payload shape

Evidence

# orderbook.py:
yes_levels = dict(msg.msg.yes)
no_levels = dict(msg.msg.no)

# orderbook_delta.py:
yes: list[tuple[DollarDecimal, FixedPointCount]] = Field(
    default=[],
    validation_alias=AliasChoices("yes_dollars_fp", "yes"),
)

Recommended fix

Make OrderbookSnapshotPayload validate yes/no directly into dict[Decimal, Decimal] via a BeforeValidator, or expose a .as_dict() cache so _apply_snapshot_inplace doesn't iterate twice.

Severity & category

medium / performance, ws

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance / hot-path concernwsWebSocket-related

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions