THREAD-SAFE AUTH & PARALLEL LOCKS IN PYTHON

Master concurrency-safe authentication across parallel test workers in Playwright with Python: eliminating race conditions in pytest-xdist, inter-process file locks with filelock, atomic storage_state writes, single-flight token renewals, and worker-isolated cache pools.

🔒 The Parallel Execution Race Condition Challenge

When accelerating Playwright test suites using parallel multi-process runners like pytest-xdist (e.g., pytest -n 4 or pytest -n auto), multiple independent Python worker processes execute concurrently. If each worker attempts to authenticate or refresh storage_state.json at startup, severe race conditions occur: multiple workers trigger duplicate login calls simultaneously, leading to rate-limiting (HTTP 429), account session invalidations, or reading corrupted partially-written JSON files. Thread-safe and process-safe authentication locks resolve this friction. By utilizing cross-process file locks via the filelock library and atomic write patterns, one worker acquires the lock, completes authentication, and flushes the storage state safely, while sibling workers wait to consume the freshly generated session.

1. Concurrency Race Conditions vs. Process-Safe File Locking
Standard Python threading locks (threading.Lock) only guard threads inside a single process. Multi-worker testing across pytest-xdist forks distinct OS processes requiring system-level file locks.
Parallel Worker Race Condition vs. FileLock Flow
WITHOUT INTER-PROCESS LOCKING (Corrupted Auth State & Account Rate Limits):
Worker 1 (gw0) ──► Check auth.json (Missing) ──► Trigger UI/API Login ──► Overwrites auth.json
Worker 2 (gw1) ──► Check auth.json (Missing) ──► Trigger UI/API Login ──► Overwrites auth.json
Worker 3 (gw2) ──► Check auth.json (Half-written) ──► json.decoder.JSONDecodeError! (CRASH)

WITH INTER-PROCESS FILELOCKING (Coordinated, Atomic & Single-Flight):
┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. All Workers Request FileLock: FileLock("storage_state.json.lock")        │
├─────────────────────────────────────────────────────────────────────────────┤
│ * Worker 1 acquires lock first:                                             │
│     - Inspects if storage_state.json exists and is valid                    │
│     - Executes single login flow ──► Writes auth.json atomically            │
│     - Releases lock                                                         │
│                                                                             │
│ * Workers 2, 3, & 4 acquire lock sequentially:                              │
│     - Inspect storage_state.json ──► Found valid & fresh!                   │
│     - Skip login immediately!                                               │
│     - Initialize BrowserContext directly with cached session                │
└─────────────────────────────────────────────────────────────────────────────┘
Architectural Advantage: Only one network authentication call executes regardless of whether you run 4, 8, or 16 parallel pytest-xdist workers.
Real-Time Example 1: Basic Inter-Process Locking with filelock
Wrap Playwright authentication inside a FileLock context manager to guarantee that only one operating system process enters the login block at any given instant.
Python (filelock Synchronized Auth Routine)
import os
import time
import tempfile
from filelock import FileLock
from playwright.sync_api import sync_playwright

storage_dir = os.path.join(tempfile.gettempdir(), "pw_threadsafe_auth")
os.makedirs(storage_dir, exist_ok=True)

auth_file = os.path.join(storage_dir, "session_state.json")
lock_file = os.path.join(storage_dir, "session_state.json.lock")

def ensure_authenticated_session():
    """Acquires an OS-level file lock to ensure only one worker authenticates."""
    lock = FileLock(lock_file, timeout=60)

    with lock:
        # Check if another worker already finished authentication while we waited
        if os.path.exists(auth_file):
            print("[Worker PID", os.getpid(), "] Session state already generated by peer. Reusing cache.")
            return auth_file

        print("[Worker PID", os.getpid(), "] Acquired lock! Performing primary authentication...")

        with sync_playwright() as p:
            api = p.request.new_context(base_url="https://httpbin.org")
            # Programmatic API login
            res = api.post("/post", data={"user": "nikita_qa", "key": "Secret9921"})
            assert res.ok

            # Create browser context to export storage state
            browser = p.chromium.launch(headless=True)
            context = browser.new_context()
            context.add_cookies([{
                "name": "enterprise_auth_token",
                "value": "TOKEN_SECURE_LOCKED_2026",
                "domain": "httpbin.org",
                "path": "/"
            }])
            context.storage_state(path=auth_file)
            context.close()
            browser.close()
            api.dispose()

        print("[Worker PID", os.getpid(), "] Authentication complete. Lock released.")
        return auth_file

# Simulate execution
state_path = ensure_authenticated_session()
print(f"Verified Session State Ready at: {state_path}")
Output: [Worker PID 4128 ] Acquired lock! Performing primary authentication... [Worker PID 4128 ] Authentication complete. Lock released. Verified Session State Ready at: /tmp/pw_threadsafe_auth/session_state.json
Real-Time Example 2: Atomic File Write Pattern to Prevent Incomplete JSON Reads
Avoid race conditions where a sibling worker reads a half-written JSON file by writing to a temporary file first and performing an atomic OS rename (os.replace).
Python (Atomic Storage State Replacement)
import os
import json
import tempfile
from playwright.sync_api import sync_playwright

def write_storage_state_atomically(context, destination_path: str):
    """Writes storage state to a temporary file and atomically moves it into place."""
    target_dir = os.path.dirname(destination_path)
    os.makedirs(target_dir, exist_ok=True)

    # Step 1: Write to an isolated temporary file in the same filesystem
    temp_target = destination_path + f".tmp.{os.getpid()}"
    context.storage_state(path=temp_target)

    # Step 2: Validate that the temporary file contains valid JSON
    with open(temp_target, "r") as f:
        data = json.load(f)
        assert "cookies" in data and "origins" in data

    # Step 3: Atomic filesystem rename (POSIX & Windows atomic replacement)
    os.replace(temp_target, destination_path)
    print(f"Atomically replaced storage state at: {destination_path}")

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    ctx = browser.new_context()
    ctx.add_cookies([{"name": "sess", "value": "ATOMIC_TOKEN_1", "domain": "example.com", "path": "/"}])

    final_dest = os.path.join(tempfile.gettempdir(), "pw_atomic", "state.json")
    write_storage_state_atomically(ctx, final_dest)

    ctx.close()
    browser.close()
Output: Atomically replaced storage state at: /tmp/pw_atomic/state.json
Real-Time Example 3: Pytest Session-Scoped FileLock Fixture with xdist
The canonical pytest-xdist pattern: execute a session-scoped fixture in conftest.py using tmp_path_factory and FileLock so parallel workers coordinate seamlessly.
Python (conftest.py Multi-Worker Fixture Pattern)
# content of conftest.py
import pytest
from filelock import FileLock
from playwright.sync_api import Playwright, Browser

@pytest.fixture(scope="session")
def session_storage_state(tmp_path_factory, worker_id: str, playwright: Playwright) -> str:
    """Coordinates authentication across parallel pytest-xdist workers."""
    # When running single-threaded (no xdist), worker_id is "master"
    if worker_id == "master":
        root_dir = tmp_path_factory.mktemp("auth_master")
    else:
        # Multiple workers share the parent temporary directory
        root_dir = tmp_path_factory.getbasetemp().parent

    state_file = root_dir / "user_storage_state.json"
    lock_file = root_dir / "user_storage_state.json.lock"

    # Synchronize all xdist workers (gw0, gw1, etc.)
    with FileLock(str(lock_file), timeout=60):
        if not state_file.is_file():
            # First worker inside lock logs in
            api = playwright.request.new_context(base_url="https://httpbin.org")
            res = api.post("/post", data={"auth": "root_user"})
            assert res.ok

            browser = playwright.chromium.launch(headless=True)
            context = browser.new_context()
            context.add_cookies([{
                "name": "auth_cookie",
                "value": "XDIST_TOKEN_SESSION_99",
                "domain": "httpbin.org",
                "path": "/"
            }])
            context.storage_state(path=str(state_file))
            context.close()
            browser.close()
            api.dispose()

    return str(state_file)

@pytest.fixture
def authenticated_context(browser: Browser, session_storage_state: str):
    """Provides a fresh context for each test pre-seeded with authenticated state."""
    context = browser.new_context(storage_state=session_storage_state)
    yield context
    context.close()
Output: [pytest-xdist] 4 workers spawned (gw0, gw1, gw2, gw3) gw0 acquired lock -> Authenticated and generated user_storage_state.json gw1, gw2, gw3 waited on lock -> Reused generated state instantly 4 passed in 1.45s
Real-Time Example 4: Single-Flight Token Renewal with TTL Checks
Inspect the Time-To-Live (TTL) of access tokens inside the storage file while holding the lock. If still valid, return immediately; if nearing expiration, perform a single-flight renewal.
Python (Time-To-Live Single-Flight Guard)
import os
import json
import time
import tempfile
from filelock import FileLock
from playwright.sync_api import sync_playwright

TOKEN_TTL_SECONDS = 3600  # 1 Hour Token Validity

def get_valid_auth_state(cache_dir: str) -> str:
    auth_file = os.path.join(cache_dir, "auth_ttl_state.json")
    lock_file = os.path.join(cache_dir, "auth_ttl_state.json.lock")

    with FileLock(lock_file, timeout=60):
        current_time = time.time()

        # Step 1: Check if file exists and token is still within valid TTL threshold
        if os.path.exists(auth_file):
            with open(auth_file, "r") as f:
                state_data = json.load(f)
                meta = state_data.get("_metadata", {})
                created_at = meta.get("created_at", 0)

                # If token has more than 5 minutes of lifetime left, reuse it
                if (current_time - created_at) < (TOKEN_TTL_SECONDS - 300):
                    print("Token cache is fresh. Reusing without network round-trip.")
                    return auth_file

        # Step 2: Token is missing or near expiration -> Perform Single-Flight Renewal
        print("Token missing or expired. Performing single-flight authentication...")
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True)
            ctx = browser.new_context()
            ctx.add_cookies([{
                "name": "bearer_sess",
                "value": f"TOK_{int(current_time)}",
                "domain": "example.com",
                "path": "/"
            }])
            raw_state = ctx.storage_state()
            # Embed metadata timestamp to track TTL
            raw_state["_metadata"] = {"created_at": current_time}

            with open(auth_file, "w") as f:
                json.dump(raw_state, f, indent=2)

            ctx.close()
            browser.close()

        return auth_file

test_dir = tempfile.gettempdir()
path_1 = get_valid_auth_state(test_dir)
# Immediate subsequent call reuses valid cache without logging in again
path_2 = get_valid_auth_state(test_dir)
Output: Token missing or expired. Performing single-flight authentication... Token cache is fresh. Reusing without network round-trip.
Real-Time Example 5: Multi-Role Concurrent Lock Partitioning
When running tests requiring distinct personas (Admin, Manager, Auditor), partition locks by role name so authentication for different roles can proceed concurrently without blocking each other.
Python (Partitioned Role-Based FileLocks)
import os
import tempfile
from filelock import FileLock
from playwright.sync_api import sync_playwright

ROLE_CREDENTIALS = {
    "admin": {"user": "admin_aarav", "pass": "AdminKey99"},
    "manager": {"user": "mgr_pooja", "pass": "ManagerKey88"},
    "auditor": {"user": "auditor_guest", "pass": "AuditKey77"}
}

def get_role_storage_state(role: str) -> str:
    """Acquires a role-specific lock so distinct roles authenticate independently."""
    base_dir = os.path.join(tempfile.gettempdir(), "pw_roles_lock")
    os.makedirs(base_dir, exist_ok=True)

    state_path = os.path.join(base_dir, f"{role}_state.json")
    lock_path = os.path.join(base_dir, f"{role}_state.json.lock")

    with FileLock(lock_path, timeout=60):
        if os.path.exists(state_path):
            return state_path

        print(f"[{role.upper()}] Initializing role credentials under dedicated lock...")
        creds = ROLE_CREDENTIALS[role]

        with sync_playwright() as p:
            api = p.request.new_context(base_url="https://httpbin.org")
            res = api.post("/post", data=creds)
            assert res.ok

            browser = p.chromium.launch(headless=True)
            ctx = browser.new_context()
            ctx.add_cookies([{
                "name": "role_cookie",
                "value": f"ROLE_TOKEN_{role.upper()}",
                "domain": "httpbin.org",
                "path": "/"
            }])
            ctx.storage_state(path=state_path)
            ctx.close()
            browser.close()
            api.dispose()

        return state_path

admin_state = get_role_storage_state("admin")
manager_state = get_role_storage_state("manager")
print("Partitioned states successfully created:")
print(f"  Admin   : {admin_state}")
print(f"  Manager : {manager_state}")
Output: [ADMIN] Initializing role credentials under dedicated lock... [MANAGER] Initializing role credentials under dedicated lock... Partitioned states successfully created: Admin : /tmp/pw_roles_lock/admin_state.json Manager : /tmp/pw_roles_lock/manager_state.json
Real-Time Example 6: Thread-Safe In-Memory Caching for Parallel Async Tests
When executing tests using Python's asyncio and async_api, protect shared in-memory authentication states using asyncio.Lock() to eliminate coroutine interleaving.
Python (asyncio.Lock for Asynchronous Workers)
import asyncio
from playwright.async_api import async_playwright

class AsyncAuthManager:
    """Asynchronous in-memory auth state manager guarded by asyncio.Lock."""
    def __init__(self):
        self._lock = asyncio.Lock()
        self._cached_state = None

    async def get_storage_state(self, playwright):
        async with self._lock:
            if self._cached_state is not None:
                print("Coroutine retrieved cached in-memory state.")
                return self._cached_state

            print("Acquired asyncio lock! Generating in-memory storage state...")
            browser = await playwright.chromium.launch(headless=True)
            context = await browser.new_context()
            await context.add_cookies([{
                "name": "async_session",
                "value": "ASYNC_VERIFIED_9921",
                "domain": "example.com",
                "path": "/"
            }])
            self._cached_state = await context.storage_state()
            await context.close()
            await browser.close()
            return self._cached_state

async def main():
    async with async_playwright() as p:
        auth_mgr = AsyncAuthManager()

        # Simulate two concurrent coroutines requesting auth state simultaneously
        task1 = asyncio.create_task(auth_mgr.get_storage_state(p))
        task2 = asyncio.create_task(auth_mgr.get_storage_state(p))

        state1, state2 = await asyncio.gather(task1, task2)
        assert state1["cookies"][0]["value"] == "ASYNC_VERIFIED_9921"
        assert state2["cookies"][0]["value"] == "ASYNC_VERIFIED_9921"
        print("Both coroutines resolved state safely without duplicate browser setups!")

asyncio.run(main())
Output: Acquired asyncio lock! Generating in-memory storage state... Coroutine retrieved cached in-memory state. Both coroutines resolved state safely without duplicate browser setups!
Real-Time Example 7: Simulating Worker Contention in Multiprocessing
A standalone demonstration using Python's multiprocessing module simulating 4 concurrent worker processes competing for the same authentication lock.
Python (Multi-Process Contention Simulation)
import os
import time
import tempfile
from multiprocessing import Process
from filelock import FileLock

def worker_task(worker_id: int, shared_lock_path: str, shared_state_path: str):
    lock = FileLock(shared_lock_path, timeout=30)
    print(f"Worker-{worker_id} (PID {os.getpid()}) attempting to acquire lock...")

    with lock:
        if os.path.exists(shared_state_path):
            print(f"  Worker-{worker_id} entered lock: State already exists. Skipped login.")
            return

        print(f"  Worker-{worker_id} entered lock: FIRST! Performing login and writing state...")
        time.sleep(0.3)  # Simulate network login latency
        with open(shared_state_path, "w") as f:
            f.write(f'{{"auth_by": "Worker-{worker_id}"}}')
        print(f"  Worker-{worker_id} released lock.")

if __name__ == "__main__":
    temp_dir = tempfile.gettempdir()
    lock_file = os.path.join(temp_dir, "contention.lock")
    state_file = os.path.join(temp_dir, "contention_state.json")

    if os.path.exists(state_file): os.remove(state_file)
    if os.path.exists(lock_file): os.remove(lock_file)

    processes = [
        Process(target=worker_task, args=(i, lock_file, state_file))
        for i in range(1, 4)
    ]

    for p in processes: p.start()
    for p in processes: p.join()

    with open(state_file, "r") as f:
        print("Final File Contents:", f.read())

    if os.path.exists(state_file): os.remove(state_file)
    if os.path.exists(lock_file): os.remove(lock_file)
Output: Worker-1 (PID 5101) attempting to acquire lock... Worker-2 (PID 5102) attempting to acquire lock... Worker-3 (PID 5103) attempting to acquire lock... Worker-1 entered lock: FIRST! Performing login and writing state... Worker-1 released lock. Worker-2 entered lock: State already exists. Skipped login. Worker-3 entered lock: State already exists. Skipped login. Final File Contents: {"auth_by": "Worker-1"}
Real-Time Example 8: Defensive Lock Handling & Stale Lock Recovery
Guard against runner aborts (e.g., CI worker killed midway) where a lock file remains stranded on disk. Use reasonable timeouts and stale lock cleanup routines.
Python (Stale Lock Auto-Purge & Recovery)
import os
import time
import tempfile
from filelock import FileLock, Timeout

def acquire_resilient_lock(lock_path: str, max_timeout: int = 20) -> FileLock:
    """Acquires lock with fallback recovery if previous process crashed holding it."""
    lock = FileLock(lock_path, timeout=max_timeout)
    try:
        lock.acquire()
        return lock
    except Timeout:
        print(f"[Warning] Lock acquisition timed out ({max_timeout}s). Checking for stale lock...")
        # Inspect lock file age
        if os.path.exists(lock_path):
            file_age = time.time() - os.path.getmtime(lock_path)
            if file_age > max_timeout:
                print(f"Purging abandoned stale lock file (Age: {int(file_age)}s)...")
                try:
                    os.remove(lock_path)
                except OSError:
                    pass
                # Retry acquisition once
                lock.acquire(timeout=max_timeout)
                return lock
        raise RuntimeError("Failed to acquire lock: resource permanently contested.")

demo_lock_path = os.path.join(tempfile.gettempdir(), "resilient_demo.lock")
active_lock = acquire_resilient_lock(demo_lock_path, max_timeout=5)
print("Resilient lock successfully acquired!")
active_lock.release()

if os.path.exists(demo_lock_path):
    os.remove(demo_lock_path)
Output: Resilient lock successfully acquired!
Real-Time Example 9: Thread-Safe Auth Methods Reference Matrix
A comprehensive reference summary comparing synchronization scopes, libraries, and failure recovery mechanisms for Playwright Python test runners.
Parallel Auth Synchronization Reference Matrix
PARALLEL AUTHENTICATION SYNCHRONIZATION MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Synchronization Mechanism    │ Primary Python Library       │ Scope & Target Architecture                             │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ Cross-Process File Locking   │ filelock.FileLock            │ Inter-process coordination for pytest-xdist workers.    │
│ Atomic File Replacement      │ os.replace(temp_path, dest)  │ POSIX/Windows atomic file switch; prevents partial read.│
│ Session Base Directory       │ tmp_path_factory.getbasetemp │ Shared directory accessible across all xdist workers.   │
│ In-Memory Coroutine Lock     │ asyncio.Lock()               │ Playwright async_api coroutine coordination.            │
│ Thread Mutex Lock            │ threading.Lock()             │ Guarding threads inside a single multi-threaded process.│
│ Partitioned Role Locks       │ FileLock(f"{role}.lock")     │ Enables concurrent login for different personas.        │
│ Lock Timeout Recovery        │ Timeout exception handler    │ Recovers from stranded locks caused by killed CI runs.  │
├──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┤
│ BEST PRACTICE EXECUTION SEQUENCE:                                                                                     │
│ 1. Acquire FileLock with timeout (e.g. 60 seconds).                                                                   │
│ 2. Double-check if storage_state.json exists and is valid (Double-Checked Locking).                                   │
│ 3. If missing/expired: Authenticate via APIRequestContext and write to temp file.                                     │
│ 4. Atomically os.replace temp file to destination storage_state.json.                                                 │
│ 5. Release FileLock so pending sibling workers can immediately read valid cached state.                               │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Engineering Best Practice: Always combine FileLock with atomic file writes (os.replace). Never allow pytest-xdist workers to write directly to shared storage_state.json files concurrently.