This document describes the architectural design of tus-java-server. It is written for developers and contributors who want to understand how the library works internally, how requests flow through the system, and where to place new functionality.
tus-java-server is an embeddable, container-native resumable upload library for Java 17+ and Jakarta EE (jakarta.servlet.*). Its design is guided by four principles:
- Single Central Service Class: A single facade—
TusFileUploadService—acts as the public API entry point and orchestrator. It manages configuration, concurrency boundaries, and extension execution without protocol-specific branching. - Protocol Composition via Extensions: Protocols are not hardcoded monoliths. Both supported protocols (Tus 1.0.0 and IETF RUFH) are composed of modular extensions extending
AbstractTusExtension. - Business Logic in Validators & Handlers: All protocol rules, request checks, and byte operations reside exclusively in dedicated
RequestValidatorandRequestHandlerimplementations. - Zero External Coordination Dependencies by Default: Out-of-the-box distributed locking uses atomic filesystem leases and POSIX sibling mutexes. No Redis, ZooKeeper, or database cluster is required to achieve multi-replica container safety.
The diagram below illustrates how incoming HTTP requests flow through the library down to the physical storage and locking abstractions:
graph TD
Client["Client (Tus / RUFH / Uppy / curl)"] -->|HTTP Request| ServletContainer["Servlet Container / Spring Boot"]
ServletContainer -->|HttpServletRequest / Response| Service["TusFileUploadService (Central Facade)"]
subgraph Service Layer ["Facade & Concurrency Boundary"]
Service -->|1. Acquire / Wait Lock| Locking["UploadLockingService (UploadLock)"]
Service -->|2. Detect Version| ProtoDetect["ProtocolVersion.AUTO (Utils.detectProtocolVersion)"]
Service -->|3. Route Pipeline| Extensions["Extension Registry (enabledFeatures)"]
end
subgraph Extension Pipeline ["Protocol Extensions"]
Extensions --> TusExt["Tus 1.0.0 Extensions<br/>(CoreProtocol, Creation, Checksum, etc.)"]
Extensions --> RufhExt["IETF RUFH Extension<br/>(ResumableUploadsForHttpProtocol)"]
Extensions --> SharedExt["Shared Extensions<br/>(CorsExtension, Expiration, Download, HttpDigests)"]
end
subgraph Processing Engine ["Business Logic Engine"]
TusExt & RufhExt & SharedExt --> Validators["RequestValidator Pipeline<br/>(Pure pre-condition validation)"]
TusExt & RufhExt & SharedExt --> Handlers["RequestHandler Pipeline<br/>(I/O Streaming, state updates, response headers)"]
end
subgraph Storage & Concurrency SPI ["Pluggable Infrastructure SPI"]
Handlers --> Storage["UploadStorageService<br/>(Disk / S3 / Azure Blob)"]
Handlers --> Locking
Storage -.-> Caching["ThreadLocalCachedStorageAndLockingService"]
Storage -.-> Concat["UploadConcatenationService"]
end
tus-java-server serves two resumable upload protocols on the exact same endpoint:
- Tus 1.0.0: The widely-adopted tus protocol standard.
- IETF Resumable Uploads for HTTP (RUFH): The official standardization draft (draft-ietf-httpbis-resumable-upload-12).
By default, the service operates in ProtocolVersion.AUTO mode: it inspects incoming HTTP headers per request (Tus-Resumable activates Tus 1.0.0; Upload-Complete or Content-Type: application/partial-upload activates RUFH).
Each protocol is built from a combination of mandatory and optional extensions:
| Protocol | Mandatory Extensions | Optional Extensions |
|---|---|---|
| Tus 1.0.0 | CoreProtocol (core OPTIONS, HEAD, PATCH) |
CreationExtension, CreationWithUploadExtension, ChecksumExtension, TerminationExtension, ExpirationExtension, ConcatenationExtension, CorsExtension, DownloadExtension |
| IETF RUFH | ResumableUploadsForHttpProtocol (OPTIONS, HEAD, GET, POST, PUT, PATCH, DELETE) |
HttpDigestsExtension (RFC 9530 digests), ExpirationExtension (max-age), CorsExtension, DownloadExtension |
- Mandatory Extensions:
CoreProtocolcannot be disabled; it defines core byte offset tracking and stream resumption for Tus 1.0.0. For RUFH requests,ResumableUploadsForHttpProtocolis the mandatory protocol handler. - Optional Extensions: Can be disabled at runtime via
service.disableTusExtension("name")or enabled on demand (e.g.service.withDownloadFeature()).
All protocol business logic is decoupled into two interfaces:
- Role: Pure, side-effect-free pre-condition verification.
- Contract: Inspects request headers and parameters. If invalid, throws a typed
TusExceptioncontaining the exact HTTP status code (e.g.,400 Bad Request,404 Not Found,409 Conflict,412 Precondition Failed,413 Payload Too Large). - Examples:
TusResumableValidator,UploadOffsetValidator,RufhCreationValidator,RufhAppendValidator.
- Role: State mutation, byte payload ingestion, response header generation, and error formatting.
- Contract:
- Standard handlers (
isErrorHandler() == false): Streams upload bytes, updates offsets in storage, sets protocol headers (Upload-Offset,Location,Upload-Limit). - Error handlers (
isErrorHandler() == true): Intercepts thrown exceptions to emit protocol-specific error payloads, such as RFC 7807 problem details (application/problem+jsoninRufhErrorHandler).
- Standard handlers (
- Examples:
CorePatchRequestHandler,RufhCreationPostRequestHandler,RufhErrorHandler.
The sequence below details the execution of TusFileUploadService.process(...):
sequenceDiagram
autonumber
actor Client
participant Service as TusFileUploadService
participant Locking as UploadLockingService
participant Extension as AbstractTusExtension
participant Validator as RequestValidator
participant Handler as RequestHandler
participant Storage as UploadStorageService
Client->>Service: HTTP Request (POST / PATCH / HEAD / DELETE)
Service->>Locking: acquireUploadLock(method, uri) (wait / retry up to 60s)
Locking-->>Service: UploadLock handle
Service->>Service: checkWasInProgress(uri)
rect rgb(240, 248, 255)
note over Service,Validator: Phase 1: Request Validation
Service->>Extension: validate(method, req, storage, locking, version)
Extension->>Validator: validate(method, req, storage)
Validator-->>Extension: OK (or throws typed TusException)
end
rect rgb(245, 255, 245)
note over Service,Storage: Phase 2: Request Execution
Service->>Extension: process(method, req, resp, storage, locking, version)
Extension->>Handler: process(method, req, resp, storage, locking)
Handler->>Storage: append(stream) / create(info) / update()
Handler-->>Service: Set response status & headers
end
opt Exception Thrown
Service->>Extension: handleError(method, req, resp, storage, locking, version, exception)
Extension->>Handler: ErrorHandler.process(...)
Handler-->>Service: Write RFC 7807 problem details / error status
end
opt Upload Finished (FINAL or COMPLETE, not PARTIAL)
Service->>Service: notifyUploadCompletionListeners(uploadInfo)
end
Service->>Locking: lock.close() (releases lock handle)
Service-->>Client: HTTP Response (201 / 204 / 409 / etc.)
File storage and metadata persistence are decoupled behind the UploadStorageService SPI.
UploadStorageService
├── DiskStorageService (Filesystem & Network Shares)
├── S3StorageService (AWS S3, MinIO, RustFS, Ceph, Cloudflare R2)
└── AzureBlobStorageService (Azure Blob Storage Block Blobs)
For local filesystems and shared network volumes, tus-java-server provides two distinct concurrency/storage combinations:
- Current / Default: Lease File Based (
DiskStorageService+LeaseFileLockingService):- Configured automatically via
withStoragePath(String). - Replaces OS kernel file locks with atomic sibling mutex directories (
<UploadId>.mutex/) and JSON lease metadata (lease.json). - Works safely across multi-replica container clusters, Kubernetes pods (
ReadWriteMany), AWS EFS, Azure Files, SMB, and NFSv3/v4 mounts without requiringrpc.statdor external databases.
- Configured automatically via
- Legacy Opt-Out: File Lock Based (
DiskStorageService+DiskLockingService):- Opt-out via
withUploadStorageService(new DiskStorageService(...)).withUploadLockingService(new DiskLockingService(...)). - Uses OS kernel-level locks (
java.nio.channels.FileLockvia POSIXfcntlor WindowsLockFileEx). - Suitable strictly for single-node deployments on local disk.
- Opt-out via
S3StorageService: Stores chunks as S3 objects and concatenates them using multipart upload copy or compose helpers (S3ConcatenationService).AzureBlobStorageService: Stages chunks directly as uncommitted Azure Block Blob blocks and commits block lists atomically upon completion. Zero-copy concatenation is supported viastageBlockFromUrl.
- Upload Concatenation SPI (
UploadConcatenationService): Supports merging parallel chunk uploads into a single final resource. Implemented natively for Disk (VirtualConcatenationService), S3 (S3ConcatenationService), and Azure (AzureBlobConcatenationService). - Upload Deduplication: Enabled via
.withUploadDeduplication(true). Completed uploads are indexed by checksum. Duplicate uploads are linked viaduplicatesUploadId. Read operations dynamically resolve to the parent upload, while write and truncation operations strictly operate on the target upload to prevent corrupting parent data. - Thread-Local Request Caching (
ThreadLocalCachedStorageAndLockingService): Enabled via.withThreadLocalCache(true). CachesUploadInfoin memory for the duration of a single HTTP request to eliminate redundant network roundtrips to S3 or Azure Blob Storage.
Custom storage engines (e.g. Google Cloud Storage, relational database BLOB stores, or custom object systems) implement the UploadStorageService interface:
- Upload Lifecycle:
create(UploadInfo, String): Allocate initial storage resources and persist the upload metadata record.append(UploadInfo, InputStream): Stream and append incoming payload chunks to storage. Persist partial progress if interrupted.getUploadInfo(UploadId)/update(UploadInfo): Retrieve and update upload metadata.getUploadedBytes(UploadId)/copyUploadTo(UploadInfo, OutputStream): Stream completed file bytes to consumers.
- Resource Termination & Lock Cleanup Contract (
terminateUpload):terminateUpload(UploadInfo)is the single authoritative method responsible for freeing all resources when an upload is deleted, cancelled, or expired. Custom implementations must:- Free physical committed data bytes and any temporary chunk buffers.
- Delete the metadata record (
.info). - Coordinate deduplication index removal or tombstoning via
deduplicationService.removeUploadFromIndex(uploadInfo)when deduplication is active. - Delegate Lock Cleanup: Call
uploadLockingService.cleanupLock(uploadInfo.getId()), ensuring no orphaned lock files, stop signals, or lease objects remain in the locking layer.
- Mandatory Locking Service:
An
UploadLockingServiceis mandatory across all storage backends. Storage services receive theirUploadLockingServicereference viasetUploadLockingService(UploadLockingService)(enforcing non-null). For unit tests or specialized embedding environments where locking is bypassed,NoOpUploadLockingServiceprovides a zero-overhead Null Object implementation. - Supporting Checksum Deduplication:
When upload deduplication is enabled (
.withUploadDeduplication(true)), storage backends must implement the following critical interface methods:deduplicate(UploadInfo, ChecksumKey): Coordinate cluster-safe deduplication upon upload completion. Storage backends typically instantiate aDeduplicationServicebacked by a customChecksumIndeximplementation to check for an existing parent, link the child upload, or register a new parent.dataExists(UploadId): Returntrueif physical committed data exists for the upload ID. The deduplication service invokes this method during parent lookup to detect out-of-band data deletions and automatically self-heal stale checksum index entries. (The default interface method returnsfalse, which disables parent reuse if not overridden.)deleteData(UploadId): Delete physical committed data bytes without removing the upload's.infometadata record. This is invoked to free physical storage when a duplicate upload is linked to an existing parent, and to purge retained parent data when the last active child terminates. (The default interface method is a no-op, which leaks storage if not overridden.)setUploadDeduplicationEnabled(boolean)/isUploadDeduplicationEnabled(): Store and expose whether deduplication is active.- Read/Write Safety Rules:
- Read operations (
getUploadedBytes,copyUploadTo) MUST checkuploadInfo.getDuplicatesUploadId()and dynamically stream bytes from the parent upload if set. - Write and mutation operations (
append,removeLastNumberOfBytes) MUST NEVER resolveduplicatesUploadIdto the parent; they must operate strictly on child storage to prevent mutating parent data.
- Read operations (
- Optional Features & Extensions:
UploadConcatenationService: Implement concatenation to support merging parallel chunk uploads into a single final resource.- Size limits: Implement
setMinAppendSize,setMaxAppendSize,setMinSize, andsetMaxUploadSizeto enforce upload payload constraints. - Cloud streaming: Implement
setCloudUploadThreadPoolSizeandsetDrainTimeoutfor asynchronous chunk uploaders. - Cleanup: Implement
close()to release underlying network clients, thread pools, or file descriptors.
Resumable uploads require exclusive concurrency control per upload resource to prevent race conditions (e.g., overlapping byte appends or simultaneous resume and delete requests).
All locking backends implement UploadLockingService and return UploadLock handles. When no concurrency control is needed, NoOpUploadLockingService acts as the null-safe implementation.
Custom distributed locking services (or extensions for GCP, Redis, DynamoDB, etc.) should extend AbstractLeaseLockingService:
classDiagram
class UploadLockingService {
<<interface>>
+lockUploadByUri(uri) UploadLock
+isLocked(id) boolean
+cleanupLock(id) void
+registerInputStream(uri, stream) void
+requestLockRelease(uri) void
}
class AbstractCloseableResourceService {
<<abstract>>
#registerShutdownHook()
#cleanupOnClose()
}
class AbstractLeaseLockingService {
<<abstract>>
#long leaseDurationMs
#long CLOCK_SKEW_SAFETY_MARGIN_MS = 2000L
#Map activeInputStreams
#ScheduledExecutorService watchdogExecutor
+lockUploadByUri(uri) UploadLock
+requestLockRelease(uri) void
#acquireOrEvictExpiredLock(id, holderId, uri)
#tryAcquireLock(id, leaseData)* UploadLock
#isLockExpired(id)* boolean
#evictExpiredLock(id)* boolean
#writeStopSignal(id)* void
#checkStopSignalForUpload(id, inputStream)* void
}
class LeaseFileLockingService {
+tryAcquireLock()
+evictExpiredLock()
}
class S3LockingService {
+tryAcquireLock()
+evictExpiredLock()
}
UploadLockingService <|.. AbstractLeaseLockingService
AbstractCloseableResourceService <|-- AbstractLeaseLockingService
AbstractLeaseLockingService <|-- LeaseFileLockingService
AbstractLeaseLockingService <|-- S3LockingService
Key Features of AbstractLeaseLockingService:
- Clock Skew Safety Margin: Built-in 2.0-second buffer (
CLOCK_SKEW_SAFETY_MARGIN_MS = 2000L) absorbs NTP drift between cluster nodes, preventing premature lease eviction. - Stream Interruption Registry: Tracks active in-flight input streams in
activeInputStreamsand interrupts them cleanly viaUtils.interruptStream(...). - Contention Dispatch & Polling Watchdog: When contention is detected, dispatches a
.stopsignal and runs a background watchdog executor (Utils.scheduleWatchdog(...)) to terminate paused streams on remote nodes. - TOCTOU-Safe Eviction with Jitter: Implements randomized backoff jitter (
jitterMinMstojitterMaxMs) to prevent thundering herd collisions when multiple nodes contend for an expired lease.
When a client loses network connectivity, the server's PATCH socket may remain stalled in a half-open state. When the client resumes with a HEAD request (or cancels with DELETE), contention is resolved across nodes:
sequenceDiagram
autonumber
actor Client
participant NodeA as Pod A (Stalled PATCH)
participant SharedStorage as Shared Storage / Bucket
participant NodeB as Pod B (Resuming HEAD)
Note over NodeA: Stalled PATCH stream holds lease lock<br/>(Stream wrapped in InterruptibleInputStream)
Client->>NodeB: HEAD /files/upload/123
NodeB->>NodeB: acquireUploadLock fails (UploadAlreadyLockedException)
NodeB->>NodeB: Enter lock wait loop (every 200ms up to 60s)
NodeB->>SharedStorage: requestLockRelease writes 123.stop signal
Note over NodeA: Watchdog polls every 1.5s and detects 123.stop
NodeA->>NodeA: watchdog calls stream.interrupt()
NodeA->>SharedStorage: Drain in-flight cloud chunks (up to 55s)
NodeA->>SharedStorage: Release lease lock & remove 123.stop
NodeB->>SharedStorage: acquireUploadLock succeeds!
NodeB->>SharedStorage: Read current Upload-Offset
NodeB-->>Client: 204 No Content (Upload-Offset: 524288)
For more details on locking mechanisms, see docs/LOCKING.md and docs/DISK_BASED_LOCKING.md.
The repository maintains high reliability across protocols and storage engines via three testing tiers:
graph TD
subgraph Testing Pyramid
Top["Conformity Test Suites (Python)<br/>• Socket-level HTTP verification against running servers<br/>• scripts/tus_conformity_test.py (50+ rules)<br/>• scripts/rufh_conformity_test.py (RFC 9530, draft-12)"]
Mid["Integration Tests (Java IT*)<br/>• Real container lifecycles via Testcontainers (Podman / Docker)<br/>• Verified in CI via mvn verify<br/>• Abstract base classes test Disk, S3 (RustFS), and Azure (Azurite)"]
Base["Unit Tests (Java *Test.java)<br/>• Pure offline Mockito isolation (< 2s)<br/>• Verified via mvn test<br/>• Strict code coverage gate (> 90% per file)"]
end
Base --> Mid --> Top
- Unit Tests (
*Test.java): Target specific classes in complete isolation with Mockito. Zero container or network requirements. Executed rapidly viamvn test -q. Coverage is verified viapython3 scripts/check-coverage.py --per-file-limit 90. - Integration Tests (
IT*): End-to-end multi-backend verification running undermvn verify -q. Tests spin up dynamic local containers via Testcontainers using either Podman or Docker. Base classes (AbstractITRufhProtocol,AbstractITTusFileUploadService) ensure identical test coverage across Disk, S3, and Azure backends. - Conformity Tests (
scripts/*_conformity_test.py): Black-box Python test suites executed against live server deployments (e.g.tus-java-server-spring-demoon port 8080) to validate strict specification compliance.
For detailed testing instructions, see docs/TESTING.md and docs/CONFORMITY_TESTING.md.
| Task | Where to Implement | Key Guidelines |
|---|---|---|
| Add a Request Validation Rule | Create a class implementing RequestValidator in the target extension's validation package. |
Keep validation side-effect-free. Throw typed TusException subclasses. Register in extension.initValidators(). |
| Add a Request Processing Action | Create a class implementing RequestHandler (or extending AbstractRequestHandler). |
Wrap streaming payload inputs in InterruptibleInputStream. Set headers on TusServletResponse. Register in extension.initRequestHandlers(). |
| Add a New Protocol Extension | Create a package under me.desair.tus.server.<extension> and extend AbstractTusExtension. |
Implement getName(), isApplicable(method, version), initValidators(), and initRequestHandlers(). Register in TusFileUploadService.initFeatures(). |
| Add a Storage Backend | Implement UploadStorageService (and optionally UploadConcatenationService). |
Implement terminateUpload (free data, metadata .info, and delegate cleanupLock). If supporting deduplication, implement deduplicate, dataExists, and deleteData, follow read/write safety rules (duplicatesUploadId), and implement a ChecksumIndex. Implement offline unit tests (*Test.java) and Testcontainers integration tests (IT*). |
| Add a Distributed Locking Provider | Extend AbstractLeaseLockingService and AbstractLeaseLock. |
Implement the template hooks (tryAcquireLock, isLockExpired, evictExpiredLock, writeStopSignal, checkStopSignalForUpload). Inherit NTP safety margins and stream interruption automatically. |