An auditable forgot-password flow needs bounded abuse state, a separate audit trail, and an explicit decision about existing sessions. Start with a shared login failure counter and add a CAPTCHA challenge when the configured threshold is reached. The bill behind that decision includes counter updates, challenge verification, recovery-message delivery, and retained audit events; retaining every attempted credential would add exposure without establishing that the recovery was legitimate.

TL;DR: For a Node.js and Express login handler, enforce the counter and challenge requirement on the server before accepting credentials, keep recovery requests from clearing that state, and treat password replacement and session invalidation as separate security decisions. OWASP describes CAPTCHA as defense in depth, not a substitute for login throttling.

Quantify retention before choosing a store. For a fixed event size, retained audit volume is the number of recorded events per day multiplied by the retention period and bytes per event. Doubling the retention period doubles that logical volume under those assumptions; it does not establish which service dominates an actual invoice. Measure event rate and encoded size first. Aggregating repetitive denials can reduce the event-count term, but sacrifices individual-attempt reconstruction. That is the storage trade-off this design must make explicit.

A logistics dispatcher recovering an account may also have an active session on another workstation. Adding challenge friction can delay access to shipment information, while leaving that other session usable after a security-driven password reset can defeat the purpose of recovery. The design therefore needs three retention boundaries: short-lived enforcement state, policy-bounded audit evidence, and independently governed session state. Their lifetimes should not be inferred from one another.

What must a login failure counter remember before a CAPTCHA challenge?

OWASP identifies the lockout threshold, observation window, and lockout duration as separate considerations, and recommends associating failed-login accounting with the account rather than relying only on the source IP. For a logistics application, that distinction matters because a network address is a poor substitute for an account identity: the enforcement decision should not assume that an address identifies one dispatcher. Source-based throttling can be an additional control.

A CAPTCHA threshold is a policy input, not a security constant. Choose it alongside an observation window and a recovery path, then test how the combination affects legitimate users. The source does not supply a universally correct threshold for this workload, and neither should an implementation example.

Count failures atomically.

A read, increment, and write sequence in separate requests can lose concurrent increments. If two Express workers both read the same value before either writes, the resulting counter can understate the failures; adding more workers does not repair that consistency error. Define one storage operation that records a failure and returns the resulting challenge state, with concurrency semantics that preserve every accepted update. A counter stored only in one worker's memory cannot coordinate the other workers. Expiration needs equally explicit semantics. A rolling lifetime extended on every failed attempt and a fixed observation window are different policies. The former can prolong friction during sustained abuse; the latter needs a defined boundary and tests around it. Neither should appear accidentally because a cache client happened to refresh an expiry. Consider an illustrative race: two workers read 2 failures, each writes 3, and the persisted count misses one failed attempt. An atomic increment would leave 4. Those are arithmetic examples, not measured traffic or recommended thresholds.

Expiry isn't housekeeping.

State Retention decision Benefit and corresponding limit
Failure counter and challenge requirement Keep through the configured enforcement window Supports current admission decisions; cannot replace historical evidence
Recovery audit events Keep for the documented audit purpose Supports reconstruction; increases retained identity-linked data
Existing sessions Apply an explicit policy at password replacement Can remove continuing access; can interrupt legitimate dispatch work

The dangerous failure mode is treating deletion of the first row as proof that the other two rows no longer matter. A reset request is not successful authentication. It must not become a way to erase an attacker's accumulated failures.

Put challenge escalation before credential acceptance

The reader looking for an Express login failure counter usually needs an ordering rule more than another middleware package. First resolve the submitted account identifier through the application's canonical identity rules, while preserving a generic public response. Next consult shared enforcement state. If policy requires a challenge, validate it on the server and bind its accepted use to the intended attempt before proceeding. Then verify credentials, record the result atomically, and create a session only after all required checks pass.

The following Python example isolates the counter transition; it is deliberately a policy function, with no claim to provide an Express server or a persistent counter. Its caller must apply the read and resulting write inside the same atomic storage operation. Both numeric arguments are deployment policy inputs.

from dataclasses import dataclass @dataclass(frozen=True) class FailureState: failures: int = 0 challenge_required: bool = False def record_failure( state: FailureState, *, challenge_threshold: int ) -> FailureState: if challenge_threshold < 1: raise ValueError("challenge_threshold must be positive") if state.failures < 0: raise ValueError("failures cannot be negative") failures = state.failures + 1 return FailureState( failures=failures, challenge_required=( state.challenge_required or failures >= challenge_threshold ), ) 

The sticky Boolean is intentional.

A failed credential check cannot remove an already required challenge. This function does not handle expiry, challenge verification, request admission limits, or successful authentication; those need explicit surrounding rules. In an Express implementation, the policy belongs behind the route handler in a shared storage boundary, and the handler must not accept a browser-provided failure count or challenge-required flag as authoritative.

Concurrency also reaches beyond increments. An in-flight attempt may have passed the admission check before another request raises the challenge requirement. Decide whether that attempt remains admitted or must recheck before session creation, and test the chosen behavior. An atomic increment alone cannot enforce a stronger rule across an entire credential-verification workflow.

A successful CAPTCHA is not a valid password.

Nor does it establish ownership of a recovery channel. Keep its scope narrow: satisfying a challenge allows the next permitted check, while credential validation, attempt throttling, and password-reset authorization continue to do their own jobs. If a required verifier is unavailable, define a controlled refusal path rather than treating an unverified challenge as accepted.

Password replacement is the session decision point

OWASP's authentication guidance calls for generic responses during authentication and recovery and describes reauthentication after risk events. Apply that separation to the dispatcher scenario: requesting a recovery message should reveal neither account existence nor whether the account has crossed an internal challenge threshold. The public response and response timing need review together, because identical words do not fix a distinguishable processing path.

Recovery initiation should also have its own abuse controls. Otherwise, moving friction to the login route leaves an adjacent way to consume delivery capacity or repeatedly disturb an account owner. This is a design requirement to validate, not a reason to reuse every login counter for every recovery operation: different operations can need different observation windows.

The meaningful security boundary is completed password replacement. At that point, choose whether existing sessions are invalidated automatically or the user is given a clearly defined revocation choice, taking account of the reason for recovery and the application's risk policy. A forgotten password and suspected account compromise need not imply identical friction, but the policy must specify the behavior.

A password write is not session revocation.

If the chosen policy requires invalidation, completion should depend on enforcing it across the session mechanisms the application actually uses. An audit event saying that revocation was requested is weaker evidence than a record that the required state change completed. Likewise, a historical audit record cannot prove that every authorization check consulted current session state. Keep those claims separate when designing the evidence.

Test the boundaries, then deploy the policy

The useful tests cross requests and storage operations. Exercise simultaneous failed attempts against the same account, retries after a response is lost, expiry at the observation-window boundary, and a recovery request interleaved with failures. Verify that a rejected or reused challenge cannot create a session and that completing password replacement enforces the selected session policy. Include nonexistent accounts when comparing public responses. These tests expose behavior that a unit test of the increment function cannot establish.

Retries deserve particular care: a repeated transport request is not automatically a second credential attempt, and arbitrary client-supplied identifiers cannot be trusted to suppress failure accounting. Document what the server considers an accepted attempt and how its storage boundary handles duplicates. The audit trail and the counter should agree on that definition, even when their retention periods differ.

Deployment should make the threshold, observation window, and session policy visible as reviewed configuration. Exercise the challenge path before enabling enforcement, and define a rollback that preserves the evidence needed to explain decisions already made. Team convenience matters here: a policy buried across several handlers is harder to review than one admission decision with documented inputs and storage guarantees.

For observability, record enough to distinguish failed authentication, challenge rejection, recovery initiation, completed password replacement, and required session invalidation. Use internal identifiers and bounded reason categories where practical. Keep passwords and reset credentials out of the audit stream; neither is necessary to explain an admission decision. Monitor challenge frequency and recovery completion together so a reduction in accepted abuse does not conceal an unusable recovery path.

The retention decision ends with deliberate deletion. Expire enforcement counters according to their policy, retain audit records only for their documented purpose, and stop keeping per-attempt detail when that purpose ends. Aggregated counts may still support trend analysis, but after individual records are gone, an investigator cannot reconstruct a particular dispatcher's sequence from those counts. Accept that loss explicitly. Preserving session security while limiting friction requires evidence about decisions, not indefinite storage of everything that touched the login form.

References

The OWASP Authentication Cheat Sheet supports the discussion of login throttling, account-based failure accounting, lockout-policy considerations, CAPTCHA limits, generic authentication and recovery responses, and reauthentication after risk events. The storage boundaries, retention equation, and deployment checks above are proposed design choices; they are not measured results or prescribed threshold values.

Further reading