Language EN FR

How to remove duplicate files in Nextcloud safely without breaking oc_filecache

Running shell deduplicators such as fdupes, rmlint, or custom rm loops inside Nextcloud's data/ directory is one of the fastest ways to desynchronize desktop clients, break WebDAV shares, and leave orphan entries in oc_filecache. This engineering runbook documents how Nextcloud tracks file state and how to clean duplicates cleanly across Nextcloud 28 to 35.

Published November 29, 2026 by André Théo Lauret (Eclipse Technology) · Maintainer of Duplicate Finder (v1.11.1, AGPL-3.0) · Companion: Duplicate Finder Pro

Direct answer for Nextcloud administrators

Never delete duplicate files directly inside Nextcloud's data directory with rm, fdupes, or rmlint. Bypassing Nextcloud's virtual filesystem leaves orphan rows in oc_filecache, freezes parent folder ETags so desktop clients upload deleted copies right back, and skips the trashbin. Clean duplicates through Duplicate Finder in the Nextcloud UI or via occ so every deletion executes native Node::delete, updates oc_filecache atomically, protects Apple Live Photos, and preserves trashbin recovery.

1. Why rm, fdupes, and rmlint directly on Nextcloud data/ corrupt sync state

On a standard Linux server, removing identical files with fdupes -dN or rmlint is routine storage hygiene. Inside Nextcloud, the raw POSIX filesystem under data/<user>/files/ is only one half of the storage layer. Every file, folder, version, share link, comment, tag, and quota total is indexed in the relational database inside oc_filecache and its companion tables.

When an administrator removes files straight from disk without going through Nextcloud's PHP virtual filesystem layer, four immediate failure modes hit production users:

Orphan rows in oc_filecache

Nextcloud continues serving database records for files that no longer exist on disk. Web UI previews return broken thumbnails, downloads trigger FileNotFoundException or HTTP 404, and storage quotas stay artificially inflated until a scan runs.

Frozen ETags cause zombie re-uploads

Nextcloud Desktop, iOS, and Android clients poll root and folder ETags stored in oc_filecache to decide whether remote contents changed. Shell deletion does not rotate parent ETags, so sync clients assume their local duplicate copy is newer or untouched and upload it straight back to the server.

Zero trashbin and broken shares

Deleting directly from disk bypasses files_trashbin and files_versions completely. Any user or public link stored in oc_share pointing at the removed file_source breaks immediately with no undo window if a user needed that copy in a shared project folder.

Broken Apple Live Photo pairs

iOS uploads Live Photos as a paired still image (IMG_1234.HEIC) plus a short companion video (IMG_1234.MOV). Naive hash deduplicators often remove one half of a pair across imported camera backups, leaving unplayable stills or orphan video files in Nextcloud Photos.

What about Btrfs or ZFS block-level deduplication?

Block-level deduplication tools such as duperemove on Btrfs/XFS reflinks or ZFS dedup operate transparently underneath the filesystem without removing logical paths. They never break oc_filecache because Nextcloud still sees every file at its original path. However, block deduplication does not reduce Nextcloud user quotas, does not unclutter duplicated folders, and does not stop desktop clients from downloading and syncing redundant copies over the network. Logical deduplication and filesystem reflinks solve different layers and can safely coexist.

2. Comparison: five approaches to Nextcloud duplicate removal

Before touching a live instance, evaluate each cleanup method across database consistency, rollback safety, sync-client behavior, and multi-user visibility. The matrix below reflects real production behavior on Nextcloud 28 through 35.

Approach Updates oc_filecache & ETags Trashbin & rollback Live Photos & Origin Folders Multi-user audit & governance Operational verdict
Shell find / rm on data/ No. Leaves orphan rows and frozen parent ETags. None. Permanent filesystem loss. None. Breaks Live Photo pairs silently. None. No structured report or audit trail. Unsafe on any live Nextcloud server.
fdupes / rmlint + occ files:scan Delayed. Desynchronized until full scan finishes. None. Bypasses files_trashbin entirely. None. Cannot inspect Nextcloud folder rules. Manual text logs only; high disk I/O window. Emergency recovery only, not routine maintenance.
Btrfs / XFS reflinks (duperemove) Transparent. Paths remain unchanged. Not applicable (no files removed). Not applicable (logical copies stay visible). Saves physical disk blocks, not Nextcloud quotas. Good complementary storage layer below Nextcloud.
Duplicate Finder OSS (v1.11.1, AGPL-3.0) Yes, atomic via native Node::delete(). Yes. Moves deleted copies to files_trashbin. Yes. Enforces Origin Folders, .nodupefinder, and Live Photo pair guards. 6 verified occ commands plus CSV and JSON reports. Recommended baseline for single and multi-user instances.
Duplicate Finder Pro (19 EUR offline) Yes, builds directly on VFS deletion pipeline. Yes, dry-run default plus --apply --confirm. Yes, plus 64-bit dHash visual photo grouping and format packs. Privacy-safe pseudonymized governance reports and audit verification. Best fit for teams, photo archives, and regulated operators.

3. How safe deletion works inside Nextcloud's VFS (Node::delete pipeline)

The open-source Duplicate Finder app (v1.11.1) maintains its own lightweight metadata index in the database table oc_duplicatefinder_finfo. Since release v1.11, the table enforces a unique path_hash index so concurrent background scans, file renames, and WebDAV uploads resolve conflicts atomically without creating duplicate index rows.

Crucially, indexing never modifies user files. When a user or administrator triggers deletion, every single file passes through six deterministic safety checks inside lib/Service/FileService.php before anything disappears:

  1. Path hygiene and traversal guard: Empty usernames, null bytes, and parent directory traversal segments (..) are rejected immediately before touching the user root folder.
  2. Dual Origin Folder enforcement: Folders declared as authoritative masters under Origin Folders are verified by OriginFolderService::assertNotProtected() both on the incoming path and again on the resolved VFS node path after symlink or mount resolution.
  3. Apple Live Photo pair guard: LivePhotoDeletionService inspects companion still and video files. Deleting a Live Photo video component alone is blocked outright; pair deletion only succeeds when explicitly allowed and another complete Live Photo pair survives elsewhere.
  4. Last-copy protection: Before removing any node, the service queries whether another live copy of that exact content hash still exists for the user. If the target is the sole surviving copy, deletion throws LastCopyProtectionException rather than wiping unique data.
  5. Native VFS $node->delete() execution: Deletion flows through OCP\Files\Node::delete(). Nextcloud atomically updates oc_filecache, recalculates folder sizes, rotates parent directory ETags so sync clients pull clean delete instructions instead of re-uploading, updates quotas, cleans up share records, and moves the file into files_trashbin.
  6. Post-delete existence verification: Because Nextcloud's HookConnector can swallow an AbortedEventException thrown by another app (such as retention or workflow locking) without rethrowing, the service verifies !$userFolder->nodeExists($effectivePath) before marking the deletion complete.
Duplicate Finder Pro Multi-User Governance Report running inside Nextcloud 35 showing per-user duplicate groups, reclaimable storage, and GDPR privacy mode
Duplicate Finder Pro companion panel running inside Nextcloud 35 above the oc_duplicatefinder_finfo index: per-user duplicate groups, reclaimable space, GDPR privacy mode, perceptual clusters, and policy controls before any VFS deletion executes.

4. Step-by-step runbook: audit and clean duplicates via occ (zero downtime)

For production Nextcloud instances with tens or hundreds of gigabytes, start from the command line using occ. Command-line audits run out-of-band from PHP-FPM request timeouts and give you exact byte counts before you delete a single copy.

Step 1: Verify database backups and inspect oc_filecache scale

Before installing any storage app or scheduling bulk cleanups, confirm that your database dump and storage snapshot completed cleanly. You can also measure the size of oc_filecache and check whether external storage mounts exist with a read-only SQL query (works on PostgreSQL and MariaDB/MySQL):

SQL (read-only diagnostic)oc_filecache & storages overview
SELECT s.numeric_id,
       s.id AS storage_id,
       COUNT(f.fileid) AS cached_entries,
       ROUND(SUM(CASE WHEN f.size > 0 THEN f.size ELSE 0 END) / 1073741824.0, 2) AS logical_gib
FROM oc_storages s
LEFT JOIN oc_filecache f ON f.storage = s.numeric_id
GROUP BY s.numeric_id, s.id
ORDER BY logical_gib DESC
LIMIT 20;

Step 2: Enable Duplicate Finder and configure mount and cron tuning

Install Duplicate Finder from the Nextcloud App Store or enable it through occ. If your instance mounts remote S3 buckets, SMB shares, or SFTP directories, disable hashing on mounted storage first so initial indexing does not stream gigabytes across your network:

Bash (Nextcloud occ)Install and tune background jobs
# Enable the open-source Duplicate Finder app (Nextcloud 28 to 35)
sudo -u www-data php occ app:enable duplicatefinder

# Optional: skip external storage mounts (SMB, SFTP, S3 external mounts)
sudo -u www-data php occ config:app:set duplicatefinder ignore_mounted_files --value=true

# Optional: tune background scan (default 432000s = 5d) and cleanup (default 172800s = 2d)
sudo -u www-data php occ config:app:set duplicatefinder backgroundjob_interval_find --value=432000
sudo -u www-data php occ config:app:set duplicatefinder backgroundjob_interval_cleanup --value=172800

Step 3: Index files and run non-destructive duplicate audits

Trigger an initial index on a single user or subfolder first to benchmark hashing throughput on your disks, then expand across the instance. Every command below is strictly read-only with respect to user files:

Bash (Nextcloud occ)Verified Duplicate Finder v1.11.1 audit commands
# 1. Index one user's Photos folder first to validate throughput
sudo -u www-data php occ duplicates:find-all --user=alice --path="./Photos"

# 2. Index all users once throughput looks healthy
sudo -u www-data php occ duplicates:find-all

# 3. Inspect duplicate volume and top reclaimable groups (table or JSON)
sudo -u www-data php occ duplicates:stats --min-size=10M --top=10 --output=table
sudo -u www-data php occ duplicates:stats --user=alice --output=json

# 4. List individual duplicate groups sorted by largest reclaimable size first
sudo -u www-data php occ duplicates:list --user=alice --sort=size-desc --min-size=10M

# 5. Instance-wide leaderboard excluding shared duplicates to avoid double-counting
sudo -u www-data php occ duplicates:list-all --min-size=100M --limit=20 --ignore-shared

# 6. Detect entire cloned directory trees (e.g. forgotten camera or laptop imports)
sudo -u www-data php occ duplicates:folders --user=alice --min-files=3 --min-size=50M

Step 4: Set protection boundaries before running cleanup

Never jump straight into bulk deletion before defining which folders represent authoritative archives. Inside the Duplicate Finder web panel, configure three layers of guardrails:

Step 5: Verify sync convergence and metadata hygiene

After cleanup, check that deleted copies appear inside the user's Nextcloud Trashbin and that connected Nextcloud Desktop clients receive clean remote deletion events without conflict notices. If you ever need to rebuild the duplicate index from scratch after major storage migrations, occ duplicates:clear --force clears only the oc_duplicatefinder_finfo metadata cache and never touches user files.

5. Repairing an instance after an unsafe filesystem cleanup

If you reached this guide after someone already ran rm, fdupes, or rmlint inside Nextcloud's data/ directory, stop any remaining shell scripts immediately and avoid blindly running occ files:scan --all during peak office hours. A full multi-terabyte scan acquires database locks and saturates disk queues while users are active.

Follow this scoped recovery order instead:

  1. Scope the repair to affected users and folders: Run occ files:scan --path="/<user>/files/<affected-folder>" per impacted directory. Scoped path scans rebuild missing oc_filecache rows and rotate parent ETags in seconds rather than hours.
  2. Purge orphaned cache rows: Once affected paths are rescanned, run occ files:cleanup to remove unreferenced entries from oc_filecache.
  3. Watch desktop clients for conflict copies: If a desktop client already re-uploaded a deleted file before the ETag rotated, let it settle, then run occ duplicates:find-all --user=<user> and remove the duplicate cleanly through the VFS so the deletion propagates to every synced device.
  4. Verify preview and appdata consistency only if thumbnails stay broken: Run occ files:scan-app-data during a maintenance window if Nextcloud Photos still displays blank previews for files that were removed out-of-band.
Bash (Nextcloud occ)Scoped post-incident recovery commands
# Rescan only the affected subfolder first (avoids full-instance I/O stall)
sudo -u www-data php occ files:scan --path="/alice/files/Imported-Backups"

# Remove unreferenced entries left behind in oc_filecache
sudo -u www-data php occ files:cleanup

# Re-index duplicates cleanly after oc_filecache is consistent again
sudo -u www-data php occ duplicates:find-all --user=alice

6. Multi-user governance, perceptual photo duplicates, and offline Pro workflows

For personal clouds and small teams looking to eliminate byte-identical files safely, the free AGPL-3.0 Duplicate Finder app handles everything described above with zero license restrictions. Larger organizations, self-hosted MSPs, universities, and photo-heavy teams eventually hit three problems that exact SHA hashing alone cannot solve:

To address those operational requirements without forcing cloud SaaS subscriptions or external phone-home telemetry, Duplicate Finder Pro ships as a one-time 19 EUR companion app verified by an offline Ed25519 signed license key (DFPRO1). All processing stays 100% inside your own Nextcloud server:

Bash (Nextcloud occ)Duplicate Finder Pro offline governance and perceptual commands
# Activate offline Ed25519 license (zero external telemetry or phone-home)
sudo -u www-data php occ duplicatefinder_pro:license:activate --key-file=/etc/nextcloud/dfpro.key
sudo -u www-data php occ duplicatefinder_pro:license:status

# Dry-run automated cleanup policy (live deletion requires --apply --confirm)
sudo -u www-data php occ duplicatefinder_pro:cleanup:run --dry-run

# Generate a GDPR-friendly governance report with SHA-256 pseudonymized usernames
sudo -u www-data php occ duplicatefinder_pro:governance:report --format=markdown --privacy-mode

# Find visually similar photos (64-bit dHash) and keep highest-resolution master
sudo -u www-data php occ duplicatefinder_pro:perceptual:scan --strategy=smart_master --dry-run

# Scan near-duplicate documents, photo bursts, media, and overlapping ZIP/TAR archives
sudo -u www-data php occ duplicatefinder-pro:scan-formats --pack=all --dry-run

# Verify cryptographic audit chain and instance health
sudo -u www-data php occ duplicatefinder_pro:audit:verify
sudo -u www-data php occ duplicatefinder_pro:health:check

If your team runs customized Nextcloud storage topologies, needs migration planning, or wants SLA-backed maintenance across internal self-hosted tooling, review our Open Source Support options or track active deliverables inside the Eclipse Client Portal.

7. Frequently asked questions

Why does deleting files directly inside Nextcloud data/ break desktop sync and oc_filecache?

Nextcloud treats the database table oc_filecache as the source of truth for file paths, sizes, permissions, shares, and folder ETags. Removing files from the OS shell with rm, fdupes, or rmlint leaves stale rows in oc_filecache and fails to rotate parent folder ETags. Desktop and mobile sync clients keep their cached tree state, hit HTTP 404 or FileNotFoundException errors, or upload the deleted duplicate files right back onto the server on the next sync pass.

Does running occ files:scan after fdupes make filesystem deletion safe?

No. Running occ files:scan after deleting files in data/ reconciles the file cache eventually, but it cannot restore deleted copies into files_trashbin, cannot preserve shares or comments linked to the removed fileid, and leaves a dangerous race window while the scan runs. On multi-terabyte instances, a full occ files:scan --all can also saturate disk I/O for hours and still break Apple Live Photo pairs.

How does Duplicate Finder protect Apple Live Photos and critical folders during cleanup?

In Duplicate Finder v1.11.1, every deletion passes through FileService::deleteFile inside Nextcloud's virtual filesystem. Before calling Node::delete(), the service enforces Origin Folder protection on both the requested and resolved paths, verifies via LivePhotoDeletionService that deleting a companion video will not orphan a still HEIC image, and applies a last-copy guard so the final surviving copy of a content hash cannot be removed by mistake.

Can Duplicate Finder skip external storage mounts like S3, SMB, or SFTP during scans?

Yes. Administrators can disable hashing on external mounts by running occ config:app:set duplicatefinder ignore_mounted_files --value=true. You can also place an empty .nodupefinder marker file inside any directory, configure Excluded Folders in Settings, or adjust the background indexing intervals through backgroundjob_interval_find and backgroundjob_interval_cleanup.

What is the difference between Duplicate Finder Open Source and Duplicate Finder Pro?

Duplicate Finder (AGPL-3.0-or-later, compatible with Nextcloud 28 to 35) covers exact content-hash deduplication, six occ audit commands, Origin Folders, Live Photo protection, Smart Keep rules, and CSV or JSON export at zero cost. Duplicate Finder Pro is a one-time 19 EUR offline Ed25519 companion app that adds policy-driven automated cleanup, privacy-safe multi-user governance reports, perceptual photo deduplication via 64-bit dHash, and multi-format similarity scans without external telemetry.

Keep oc_filecache healthy and automate Nextcloud deduplication offline

Start with Duplicate Finder v1.11.1 (AGPL-3.0) for safe VFS deletion, Origin Folders, Live Photo protection, and occ audits on Nextcloud 28 to 35. Upgrade to Duplicate Finder Pro for a one-time 19 EUR offline Ed25519 license when you need automated dry-run cleanup policies, pseudonymized governance reports, and perceptual photo deduplication.