This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-workmanager-bgtask-reentrancy-barrier

KMP WorkManager and BGTaskScheduler Idempotent Re-entrancy Barrier

Enforces an atomic, distributed transaction barrier across shared Kotlin Multiplatform codebases to eliminate race conditions between Android WorkManager retries and iOS BGTaskScheduler invocations. Guarantees mutually exclusive background job execution, deterministic state fencing, and monotonic lease fencing against stale task instances.

Prohibited Anti-Pattern: Unsynchronized cross-platform background dispatch permitting overlapping worker execution and non-idempotent payload corruption

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP WorkManager and BGTaskScheduler Idempotent Re-entrancy Barrier - Enforces an atomic, distributed transaction barrier across shared Kotlin Multiplatform codebases to eliminate race conditions between Android WorkManager retries and iOS BGTaskScheduler invocations. Guarantees mutually exclusive background job execution, deterministic state fencing, and monotonic lease fencing against stale task instances.
globs: shared/src/commonMain/**/*.kt, shared/src/androidMain/**/*.kt, shared/src/iosMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-workmanager-bgtask-reentrancy-barrier"
---

# KMP WorkManager and BGTaskScheduler Idempotent Re-entrancy Barrier

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized cross-platform background dispatch permitting overlapping worker execution and non-idempotent payload corruption

## System Constraints
You are a Principal Software Architect enforcing idempotent background execution and distributed re-entrancy barriers in Kotlin Multiplatform (KMP). Android WorkManager and iOS BGTaskScheduler execute under radically different OS lifecycle constraints, suspension models, and retry triggers. You must enforce atomic lease-fencing, deterministic check-pointing, and monotonic version validation in shared domain layers to prevent duplicate writes, simultaneous background execution races, and ghost task persistence across platform bridges.

## Strict Guidelines
- Engineers MUST ALWAYS enforce an atomic database-backed or secure-storage-backed lease token (fencing token) prior to executing any background payload in commonMain.
- Engineers MUST NOT invoke platform-specific schedulers (androidx.work.ListenableWorker or platform.BackgroundTasks.BGTask) directly from business logic; all tasks must pass through an abstracted JobQueueCoordinator enforcing mutual exclusion.
- Code SHOULD verify monotonically increasing epoch fence timestamps at every suspension point to detect whether a competing worker or expired task has superseded the current execution context.
- Services MUST release acquired leases inside guaranteed 'finally' blocks or via structured CoroutineScope cancellation handlers, marking the terminal state as either COMPLETED or EXPIRED.
- Components NEVER execute raw mutating network or persistence I/O without asserting that the background task lease is still valid and unexpired immediately before dispatch.

## Bad vs Good Implementations
### Enforcing Atomic Fencing Barrier in KMP Background Task

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The worker executes domain operations without checking if another background execution instance (e.g., an uncancelled Android worker retry or an overlapping iOS BGTask execution) is already active. This leads to duplicate transactional side effects and inconsistent local/remote state.
```kotlin
// ANTI-PATTERN: Direct, unsynchronized payload execution in shared KMP background bridge
class SyncBackgroundWorker(private val repository: DataRepository) {
    suspend fun doWork(payloadId: String): Boolean {
        // Race condition: Both WorkManager and BGTaskScheduler can fire simultaneously
        // No fence token, no monotonic state validation, no re-entrancy check.
        val pendingItems = repository.getPendingItems(payloadId)
        repository.syncItems(pendingItems) // Can duplicate records or corrupt remote state
        return true
    }
}
```

#### Production Standard (Correct)
> **Standard**: Acquires a time-bounded monotonic fencing token via JobFenceStore prior to execution. Verifies the token before performing I/O, ensuring that overlapping workers, expired leases, or platform-level scheduler retries do not execute concurrently or commit stale mutations.
```kotlin
// PRODUCTION-GRADE: Atomic lease fence barrier with re-entrancy protection and token invalidation
interface JobFenceStore {
    suspend fun acquireFence(jobKey: String, leaseDurationMs: Long): Long? // Returns monotonic fence token
    suspend fun releaseFence(jobKey: String, fenceToken: Long): Boolean
    suspend fun isFenceValid(jobKey: String, fenceToken: Long): Boolean
}

class IdempotentBackgroundWorker(
    private val fenceStore: JobFenceStore,
    private val repository: DataRepository
) {
    suspend fun doWork(jobKey: String, payloadId: String): Result<Unit> = runCatching {
        val leaseDurationMs = 30_000L
        val fenceToken = fenceStore.acquireFence(jobKey, leaseDurationMs)
            ?: throw IllegalStateException("Task $jobKey already running or lock contention")

        try {
            val pendingItems = repository.getPendingItems(payloadId)
            
            // Monotonic invariant barrier verification before mutating mutation
            check(fenceStore.isFenceValid(jobKey, fenceToken)) { "Fence invalidated by superseded runner" }
            repository.syncItems(pendingItems)
        } finally {
            fenceStore.releaseFence(jobKey, fenceToken)
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP WorkManager and BGTaskScheduler Idempotent Re-entrancy Barrier

KMP WorkManager and BGTaskScheduler Idempotent Re-entrancy Barrier defines an industrial-grade behavioral standard for mobile engineering. Enforces an atomic, distributed transaction barrier across shared Kotlin Multiplatform codebases to eliminate race conditions between Android WorkManager retries and iOS BGTaskScheduler invocations. Guarantees mutually exclusive background job execution, deterministic state fencing, and monotonic lease fencing against stale task instances. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unsynchronized cross-platform background dispatch permitting overlapping worker execution and non-idempotent payload corruption Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnsynchronized cross-platform background dispatch permitting overlapping worker execution and non-idempotent payload corruptionCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enforce an atomic database-backed or secure-storage-backed lease token (fencing token) prior to executing any background payload in commonMain.

Engineers MUST ALWAYS enforce an atomic database-backed or secure-storage-backed lease token (fencing token) prior to executing any background payload in commonMain.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT invoke platform-specific schedulers (androidx.work.ListenableWorker or platform.BackgroundTasks.BGTask) directly from business logic

Engineers MUST NOT invoke platform-specific schedulers (androidx.work.ListenableWorker or platform.BackgroundTasks.BGTask) directly from business logic; all tasks must pass through an abstracted JobQueueCoordinator enforcing mutual exclusion.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code SHOULD verify monotonically increasing epoch fence timestamps at every suspension point to detect whether a competing worker or expired task has superseded the current execution context.

Code SHOULD verify monotonically increasing epoch fence timestamps at every suspension point to detect whether a competing worker or expired task has superseded the current execution context.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST release acquired leases inside guaranteed 'finally' blocks or via structured CoroutineScope cancellation handlers, marking the terminal state as either COMPLETED or EXPIRED.

Services MUST release acquired leases inside guaranteed 'finally' blocks or via structured CoroutineScope cancellation handlers, marking the terminal state as either COMPLETED or EXPIRED.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER execute raw mutating network or persistence I/O without asserting that the background task lease is still valid and unexpired immediately before dispatch.

Components NEVER execute raw mutating network or persistence I/O without asserting that the background task lease is still valid and unexpired immediately before dispatch.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is KMP WorkManager and BGTaskScheduler Idempotent Re-entrancy Barrier critical for AI coding assistants?

Enforces an atomic, distributed transaction barrier across shared Kotlin Multiplatform codebases to eliminate race conditions between Android WorkManager retries and iOS BGTaskScheduler invocations. Guarantees mutually exclusive background job execution, deterministic state fencing, and monotonic lease fencing against stale task instances. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unsynchronized cross-platform background dispatch permitting overlapping worker execution and non-idempotent payload corruption) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

KMP