perf(sdk): cache Resource.__hash__; OTLP encoders re-serialize the Resource for every span and log record
Maintainers usually reply within 2 days
Nobody has claimed this yet.
Assessment
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Newbie friendliness
- 78/100
- Issue type
- Feature
- Clarity
- Clearly specified
- Activity status
- Active
- Tech stack
- python
- Domain
- backend, performance
Research direction
Read the Resource.__hash__ implementation and the Resource tests; the issue does not name a test file, so locate the tests covering Resource equality and hashing. Add a check that repeated hashing returns the same value while preserving equality behavior, and run the focused Resource tests. Done means the hash is reused after its first computation and existing Resource behavior still passes.
Written by the indexing model from the issue text.
Description
Is your feature request related to a problem?
Resource.__hash__ recomputes its hash from a JSON dump of all attributes on every call:
def __hash__(self) -> int:
return hash(
f"{dumps(self._attributes.copy(), sort_keys=True, default=_json_default)}"
f"|{self._schema_url}|{self._schema_url_conflict}"
)
The OTLP encoders group records by resource, using the Resource as a dict key once per record:
_encode_resource_spans:sdk_resource_spans[sdk_span.resource][sdk_instrumentation].append(pb2_span)_encode_resource_logs:sdk_resource_logs[readable_log.resource][sdk_instrumentation].append(pb2_log)
So every exported span and log record copies, sorts and JSON-encodes the entire resource, even though a process almost always has a single, unchanging Resource. With the usual resource attributes (service, host, process, k8s/cloud detectors), this is a noticeable share of export CPU in high-throughput services.
Observed on opentelemetry-sdk 1.41.0; main has the same uncached implementation. No existing issue found (related but distinct: #5576/#5577, #5591).
Describe the solution you'd like
I'd like Resource to compute its hash once and reuse it.
A Resource is effectively immutable after construction (its attributes are a BoundedAttributes, there is no public mutator, and merge returns a new Resource), so the hash can be computed eagerly in __init__ or lazily on the first __hash__ call. Lazy caching keeps construction cost unchanged:
def __hash__(self) -> int:
cached = self.__dict__.get("_hash")
if cached is None:
cached = self._hash = hash(
f"{dumps(self._attributes.copy(), sort_keys=True, default=_json_default)}"
f"|{self._schema_url}|{self._schema_url_conflict}"
)
return cached
Describe alternatives you've considered
- Cache in the OTLP encoders instead, e.g. group by
id(resource)or keep a per-batch resource → key map. That fixes only the OTLP path; other exporters and processors that hash aResourcestill pay the cost, so fixing it inResourceitself is simpler and benefits every consumer. - Eagerly compute the hash in
Resource.__init__. It works too, but it charges every construction, including the temporary resources made during detector merging, which may never be hashed. - Leave it to users to monkeypatch
Resource.__hash__. That's what we do today; it works but depends on private attributes and could break on upgrades.
Additional Context
- Similar fix in the Collector: open-telemetry/opentelemetry-collector-contrib#50955 caches the resource attribute hash per resource in the signaltometrics connector instead of rehashing on every signal.
- Related Resource hashing issues in this repo (correctness, not performance): #5576 / #5577 (bytes-valued attributes), #5591.
- Versions: observed on opentelemetry-sdk 1.41.0;
mainhas the same uncached__hash__.
Would you like to implement a fix?
None
Tip
React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it. Learn more here.
- Dominant language
- Python
- Stars
- 2.7k
- Forks
- 1.1k
- Avg merge
- 3d 23h
- Merged PRs (30d)
- 20
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from open-telemetry/opentelemetry-python
-
References to Archived open-telemetry/otepsPossibly taken @RjyavardhanSingh claimed this 3 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
open-telemetry/opentelemetry-python#5984 · 1 comment ·
Maintainers usually reply within 2 days
-
Autoconfiguration rejects OTEL_EXPORTER_OTLP_PROTOCOL=http/jsonPossibly taken @WendeelMarinho claimed this 4 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
open-telemetry/opentelemetry-python#5981 ·
Maintainers usually reply within 2 days
-
MeterProvider raises ValueError on empty or uppercase OTEL_METRICS_EXEMPLAR_FILTERPossibly taken @bishalde claimed this 10 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 83/100
open-telemetry/opentelemetry-python#5948 · 3 comments ·
Maintainers usually reply within 2 days
-
W3CBaggagePropagator drops a list-member over 4096 bytes that W3C Baggage requires it to propagatePossibly taken @codedbyadiiii claimed this 22 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 70/100
open-telemetry/opentelemetry-python#5913 ·
Maintainers usually reply within 2 days
-
otel.sdk.processor.{span,log}.queue.capacity uses synchronous UpDownCounter recorded once in __init__May be free again A pull request for this issue was closed without being merged. Open
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
open-telemetry/opentelemetry-python#5891 ·
Maintainers usually reply within 2 days
All issues in open-telemetry/opentelemetry-python
Similar issues
-
Make the "%" unit spacing the same in the web and in A10Possibly taken @kragent66-glitch claimed this today. Openbug good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
maiychrus25/OpenTea-DX-OS#226 · 1 comment ·
-
ci severity: low
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
TMHSDigital/Spackle#205 ·
Maintainers usually reply within 1 day
-
pkg:lgm type:chore upstream-gaussx
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
jejjohnson/pyrox#610 ·
Maintainers usually reply within 1 day
-
changelog investigate
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
ramnes/notion-sdk-py#523 ·
-
good first issue
Difficulty 1/5 1-3 hours Newbie friendliness 78/100