This document provides architectural details, distributed concurrency mechanics, network mount configurations, and migration/opt-out instructions for filesystem-backed locking in tus-java-server.
Starting in version 2.0.0, LeaseFileLockingService is the default locking implementation instantiated by TusFileUploadService.withStoragePath(String).
The legacy DiskLockingService relies on OS kernel-level file locks (java.nio.channels.FileLock via POSIX fcntl on Linux and LockFileEx on Windows). While reliable on local disks, kernel file locks frequently fail on shared network storage (NFS, AWS EFS, Azure Files, SMB/CIFS):
- Unprivileged Containers & Kubernetes: Pods running in isolated network namespaces lack
rpc.statd/ NLM daemons, causingFileChannel.tryLock()to fail withIOException: No locks available(ENOLCK). nolockMounts: Shares mounted with thenolockperformance option (e.g. AWS EFS defaults) ignore or reject POSIX file locks.- Ungraceful Crashes: Pod crashes (
kill -9, OOM killer, node eviction) leave locks stuck in NFS server state for minutes or indefinitely. - Cross-Pod Coordination: Kernel file locks are tracked in OS memory and do not coordinate cleanly across multi-replica container clusters.
LeaseFileLockingService replaces OS kernel locks with atomic sibling mutex directory creation (mkdir) and JSON lease files with background heartbeat renewal. This provides zero external dependencies (no Redis, ZooKeeper, or etcd cluster required) and works seamlessly on both local disks and distributed network shares.
Locks are structured as a dedicated directory containing a JSON lease metadata file, synchronized via a transient sibling mutex directory:
<storagePath>/locks/
├── <UploadId>.lock/ # Dedicated lock directory (contains lease.json)
│ └── lease.json # JSON lease metadata (holderId, expiresAt, acquiredAt)
├── <UploadId>.mutex/ # Transient sibling atomic mutex directory (age <= 5s)
└── <UploadId>.stop # Empty signal file for lock contention interruption
{
"holderId": "pod-tus-backend-7d9c6-thread-14",
"requestUri": "/files/upload/018f3b2a-7140-7e1d-8f92-5cb640d28362",
"leaseDurationMs": 30000,
"acquiredAt": 1723401204567,
"expiresAt": 1723401234567,
"lockPath": "/mnt/uploads/locks/018f3b2a-7140-7e1d-8f92-5cb640d28362.lock",
"stopPath": "/mnt/uploads/locks/018f3b2a-7140-7e1d-8f92-5cb640d28362.stop"
}- Sibling Mutex Isolation (
<UploadId>.mutex/): All state-modifying operations (acquisition, in-place takeover, release, and cleanup) acquire<UploadId>.mutex/via atomicFiles.createDirectory. Because the mutex is a sibling of<UploadId>.lock/, the lock directory contains onlylease.json, avoiding nested directory deletion races (DirectoryNotEmptyException) and Windows handle locking conflicts. - In-Place Takeover (Zero Directory Moves): Rather than moving or displacing the lock directory during eviction (which creates a TOCTOU hole where the directory temporarily vanishes from disk), expired locks are updated in place directly inside
<UploadId>.lock/under mutex protection. - Fencing & Ownership Verification: Both
lock.close()and heartbeat renewals verify thatholderIdinlease.jsonmatches the current holder before modifying or deleting files, ensuring a paused node never corrupts a successor's active lease. - 5-Second Crash Recovery: Stale mutex directories left behind by crashed nodes are detected via
now - mtime >= 5000ms, cleanly recovered, and retried.
To acquire or take over a lock:
- Extract
UploadIdfrom the request URI. - Acquire sibling mutex
<storagePath>/locks/<UploadId>.mutex/viaFiles.createDirectory.-
Collision (Already Exists): If
mtimeis $< 5$s old, another live node is modifying the lock$\rightarrow$ throwUploadAlreadyLockedException. If $\ge 5$s old, clean up stale mutex and retry.
-
Collision (Already Exists): If
- Under mutex protection:
- If
<UploadId>.lock/lease.jsonexists and is unexpired: lock is actively held on another replica$\rightarrow$ throwUploadAlreadyLockedException. - If
<UploadId>.lock/does not exist: create directory. - If
lease.jsonis missing or expired: write updatedlease.jsonvia a temporary file and atomically rename it into place (Files.movewithATOMIC_MOVE, REPLACE_EXISTING). This prevents concurrent read-only queries (likeisLocked()) from ever observing an empty (0-byte) or partially written JSON file during disk flushes. - Start background heartbeat daemon (renews every
$\text{leaseDuration} / 3$ ) and returnLeaseFileUploadLock.
- If
- Release
<UploadId>.mutex/.
When an active upload completes or is aborted:
- Stop background heartbeat daemon.
- Acquire sibling mutex
<UploadId>.mutex/. - Read
lease.jsonand verifyholderId == this.holderId. - If ownership matches: delete
lease.jsonand delete<UploadId>.lock/. - Release
<UploadId>.mutex/.
Active streaming uploads periodically renew their lease by updating expiresAt in lease.json every holderId ownership under the sibling mutex to ensure it aborts if the lease was taken over after a long pause.
When a client sends a HEAD or DELETE request to resume or cancel an upload while a stalled PATCH stream holds the lock:
- The resuming server catches
UploadAlreadyLockedExceptionand callsrequestLockRelease(requestUri). - It interrupts any JVM-local stream and writes
<storagePath>/locks/<UploadId>.stop. - A background watchdog thread on the holding replica (polling every 1.5 seconds) detects
.stopand callsstream.interrupt(). - The stalled
PATCHstream aborts and releases its lock. The server's 60-second retry budget ($300 \times 200\text{ms}$ , configurable viawithLockWaitTimeout(Duration)) allows theHEADorDELETErequest to acquire the lock and succeed seamlessly.
Distributed lease evaluation across nodes relies on expiresAt timestamps written to lease.json. When sharing a network volume across multiple pods or virtual machines, all host nodes MUST synchronize system clocks using NTP (Network Time Protocol) or cloud time synchronization daemons (chrony). To absorb inevitable minor NTP drift, LeaseFileLockingService incorporates a built-in 2.0-second safety margin (CLOCK_SKEW_SAFETY_MARGIN_MS = 2000L inherited from AbstractLeaseLockingService), ensuring that a node whose clock is slightly ahead will never prematurely evict a live peer's lease. Clock drift between cluster nodes should remain well within
For multi-replica deployments connecting to shared NFS storage (e.g. AWS EFS, Azure NetApp Files, on-premise NFS):
mount -t nfs4 -o rw,hard,intr,rsize=1048576,wsize=1048576,actimeo=3 nfs-server:/data/uploads /mnt/tus-uploadshard,intr: Prevents silent I/O failure on transient network disconnects and allows graceful thread interruption.actimeo=3: Attribute caching timeout of 3s ensures.stopsignal files and lease renewals propagate rapidly across pods.rsize=1048576,wsize=1048576: 1MB I/O buffers for maximum streaming append throughput.
For Windows Server SMB shares or Azure Files SMB:
New-SmbMapping -RemotePath "\\smb-server\uploads" -LocalPath "Z:" -Persistent $TrueIf you are running single-node deployments on local disk and specifically require legacy OS-level FileLock (fcntl / LockFileEx), you can easily opt out of LeaseFileLockingService and restore DiskLockingService.
String storagePath = "/var/data/tus-uploads";
TusFileUploadService tus = new TusFileUploadService()
.withUploadStorageService(new DiskStorageService(storagePath))
.withUploadLockingService(new DiskLockingService(storagePath)) // Opt-out to legacy FileLock
.withUploadDeduplication(true)
.withThreadLocalCache(true);@Configuration
public class TusConfig {
@Bean
public TusFileUploadService tusFileUploadService(@Value("${tus.storage.path}") String storagePath) {
return new TusFileUploadService()
.withUploadUri("/files/upload")
.withUploadStorageService(new DiskStorageService(storagePath))
.withUploadLockingService(new DiskLockingService(storagePath)) // Opt-out to legacy FileLock
.withUploadDeduplication(true)
.withThreadLocalCache(true);
}
}