bcquality/microsoft/knowledge/performance/avoid-growing-globals-in-singleinstance-subscribers.md
Jesper Schulz-Wedde 78eeb86a37 Promote performance knowledge from community to Microsoft layer
Pure git-mv relocation of all 7 performance articles from community/knowledge/performance/ to microsoft/knowledge/performance/. No content changes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-06-25 14:03:39 +02:00

1.6 KiB

bc-version domain keywords technologies countries application-area
all
performance
singleinstance
subscriber
event
memory
session
al
w1
all

Avoid growing globals in SingleInstance subscribers

Contributions welcome — open a PR to refine or extend this article.

Description

A codeunit with SingleInstance = true is allocated once per session and lives until the session ends. Global variables on it are never collected between event fires. A subscriber that accumulates data into a global — buffering payloads, appending to a list, caching without a cap — steadily grows its session footprint for the entire user session. The symptom is memory that only recovers on sign-out, and it surfaces only on long-running sessions.

Best Practice

Keep the global footprint on a SingleInstance subscriber bounded and intentional: a handful of flags, a setup record, a bounded cache with a maximum size. When cross-event state is genuinely needed, define an explicit reset point — end of a business process, arrival of a specific terminal event — that clears the growing collection.

See sample: avoid-growing-globals-in-singleinstance-subscribers.good.al.

Anti Pattern

A SingleInstance subscriber that appends each event's payload to a global list, dictionary, or temporary record without a cap or cleanup trigger. The list grows for hours, memory pressure builds quietly, and debugging the root cause on a live environment is substantially harder than noticing the unbounded append in code review.

See sample: avoid-growing-globals-in-singleinstance-subscribers.bad.al.