Interview QA
Interviewer: tell me all ways to cleanup memory in Linux?
Cleaning up memory in Linux is a critical skill for DevOps and system engineers, especially when systems are under memory pressure or to optimize performance. Here’s a detailed breakdown of all major ways to clean up or free memory in Linux:
🔧 1. Clear PageCache, dentries, and inodes (drop_caches)
# Sync before clearing caches (recommended)
sync
# Clear PageCache only
echo 1 > /proc/sys/vm/drop_caches
# Clear dentries and inodes
echo 2 > /proc/sys/vm/drop_caches
# Clear PageCache, dentries, and inodes
echo 3 > /proc/sys/vm/drop_caches✅ Best used for reclaiming cache memory (won’t kill processes).
🔥 2. Kill High-Memory Processes
Find and kill memory-hungry processes:
# Find top 10 memory-consuming processes
ps aux --sort=-%mem | head
# Kill a specific process
kill -9 <PID>✅ Useful when a specific process is hogging memory.
🧠 3. Free Up Swap Memory
To clear swap and move data back to RAM:
# Disable swap
swapoff -a
# Re-enable swap
swapon -a✅ Helpful when swap usage is high and you want to reset it.
🚰 4. Flush Disk Buffers and Cache (sync)
sync✅ Ensures all data is written to disk before clearing caches.
🗂 5. Use systemctl restart or service to Restart Services
systemctl restart or service to Restart ServicesIf a service is leaking memory:
systemctl restart apache2 # Example: restart Apache✅ Restarts the service and reclaims memory.
📉 6. Use oom_kill or earlyoom
oom_kill or earlyoomConfigure OOM Killer or use earlyoom for automated memory cleanup:
earlyoom: kills processes when memory is critically low./proc/sys/vm/oom_kill_allocating_task: enable OOM killer tuning.
📦 7. Clear Cache via free and sync combo
free and sync comboCheck usage:
free -hForce cleanup:
sync; echo 3 > /proc/sys/vm/drop_caches🧽 8. Memory Leak Debugging and Cleanup
Use tools like:
valgrindtop,htopsmemvmstatmeminfoin/proc
✅ Identify memory leaks for long-term cleanup.
🧹 9. Reboot the System
reboot✅ Last resort but guarantees memory reset.
🛠 BONUS: Automate with Cron
You can set periodic cache cleanup:
# Add to crontab (runs daily at 2 AM)
0 2 * * * root sync; echo 3 > /proc/sys/vm/drop_cachesSummary Table
drop_caches
Free file system cache
Safe
Kill processes
Reclaim memory from apps
Medium
swapoff && swapon
Clear swap
Medium
sync
Flush disk buffers
Safe
Restart services
Reclaim app memory
Low
oom_kill / earlyoom
Auto kill on low memory
Low-Medium
Reboot
Complete cleanup
High
Let me know if you want a bash script or systemd timer to automate these.
interviewer: tell me all ways to cleanup CPU in Linux?
Cleaning up CPU usage in Linux is essential when your system becomes sluggish due to high processor load. If an interviewer asks "Tell me all ways to clean up CPU in Linux?", here’s a comprehensive, categorized answer you can give:
✅ 1. Identify High CPU Consumers
Start by finding the root cause:
top # Real-time CPU usage
htop # Better UI (requires install)
ps aux --sort=-%cpu | headCheck system load:
uptime
vmstat 1 5🔥 2. Kill or Nice High CPU Processes
Kill a high-CPU process:
kill -9 <PID>Lower a process’s CPU priority (increase niceness):
renice +10 <PID> # Values from -20 (highest) to 19 (lowest priority)✅ Prevents process from hogging CPU without killing it.
📉 3. Limit CPU Usage with cpulimit
cpulimitInstall and run:
sudo apt install cpulimit # or use yum/dnf on RHEL-based distros
cpulimit -p <PID> -l 30 # Limit to 30% CPU✅ Helps manage resource-hungry apps like ffmpeg or compression tools.
📊 4. Use taskset to Pin Process to Specific CPU Core
taskset to Pin Process to Specific CPU Coretaskset -c 0,1 <command> # Bind to core 0 and 1✅ Useful for isolating CPU-intensive apps.
⚙️ 5. Check and Fix Stuck Services or Daemons
Use systemctl or service:
systemctl status <service>
systemctl restart <service>✅ Some background services can go rogue and consume CPU.
🐞 6. Identify and Debug CPU Spikes
Use
perf top,pidstat, orstraceto trace syscalls.Investigate with:
pidstat -u 1
strace -p <PID>✅ Helps when CPU is high but process is unknown or stuck.
🧠 7. Reduce Unnecessary Background Services
List all enabled services:
systemctl list-unit-files | grep enabledDisable unneeded ones:
systemctl disable <service>✅ Frees both CPU and RAM.
📦 8. Uninstall Heavy or Unused Applications
For example:
sudo apt remove apache2✅ Avoid resource-hogging software that isn’t needed.
🪫 9. Use Cgroups to Restrict CPU for Apps
Create a CPU-limited group (example with systemd):
# Create systemd slice
mkdir /sys/fs/cgroup/cpu/myapp
# Limit CPU usage to 20%
echo 20000 > /sys/fs/cgroup/cpu/myapp/cpu.cfs_quota_us
echo 100000 > /sys/fs/cgroup/cpu/myapp/cpu.cfs_period_us
# Move process to cgroup
echo <PID> > /sys/fs/cgroup/cpu/myapp/tasks✅ Fine-grained control over CPU.
🔄 10. Reboot (Last Resort)
reboot✅ Clears up stuck processes and resets everything.
🔐 BONUS: System Optimization Tips
Enable performance governor only when needed (
cpupower frequency-set)Tune kernel parameters:
/etc/sysctl.confUse lightweight alternatives (e.g., nginx instead of apache)
🧾 Summary Table
Kill process
Stops high CPU app
Medium
Renice/CPULimit
Lowers app priority/CPU
Safe
Restart service
Fixes stuck services
Low
Cgroups
Isolate and limit apps
Low-Medium
Disable background services
Frees system resources
Low
Use taskset
CPU core binding
Safe
Debug with strace, perf
Advanced troubleshooting
Advanced
Reboot
Resets CPU load
High
Would you like a shell script to monitor and auto-restrict high-CPU processes?
interviewer: tell me all ways to cleanup Disk in Linux?
If an interviewer asks "Tell me all ways to clean up disk in Linux?", they’re testing your practical knowledge of storage management, cleanup commands, and troubleshooting. Here's a complete and structured answer:
🧹 All Ways to Clean Up Disk in Linux
🔍 1. Find Out What’s Using Disk Space
Check disk usage:
df -hFind largest directories/files:
du -h --max-depth=1 / # Top-level usage
du -ah / | sort -rh | head -n 20 # Top 20 largest files
ncdu / # Interactive disk usage viewer✅ First step before cleanup: know where the space is going.
📦 2. Clean Package Manager Cache
For Debian/Ubuntu:
sudo apt clean # Remove all cached .deb files
sudo apt autoremove # Remove unneeded packagesFor RHEL/CentOS:
sudo yum clean all
sudo dnf autoremove✅ Recovers hundreds of MBs or even GBs from package cache.
🧹 3. Clear System Logs
sudo journalctl --vacuum-time=7d # Keep only last 7 days
sudo journalctl --vacuum-size=500M # Or limit size
sudo rm -rf /var/log/*.gz /var/log/*.[0-9] /var/log/*.log.old✅ System logs can grow indefinitely if not rotated.
📁 4. Delete Temporary Files
sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*✅ Regular temp files can accumulate and waste space.
🧹 5. Clear Trash/Recycle Bin
rm -rf ~/.local/share/Trash/*✅ Especially relevant for desktop environments (GNOME/KDE).
🔧 6. Uninstall Unused Software
List installed packages:
dpkg --get-selections | grep -v deinstallRemove unused ones:
sudo apt remove <package>✅ Frees both binaries and dependencies.
🧱 7. Identify and Clean Orphaned Packages
Debian/Ubuntu:
sudo deborphanRedHat-based:
sudo package-cleanup --leaves✅ Removes packages no longer needed.
🐳 8. Clean Docker Resources
docker system prune -a # Remove all unused containers/images/networks
docker volume prune # Remove dangling volumes✅ Docker can eat up gigabytes of space if left unchecked.
🧼 9. Remove Old Kernels
On Ubuntu:
sudo apt --purge autoremove✅ Old kernels not in use can be safely removed.
📦 10. Clean Snap Packages (Ubuntu)
sudo snap list --all
sudo snap remove <old-version>Use a script:
snap list --all | awk '/disabled/{print $1, $2}' |
while read snapname version; do sudo snap remove "$snapname" --revision="$version"; done✅ Snap stores multiple versions by default.
🧠 11. Find and Delete Duplicate Files
Install fdupes:
sudo apt install fdupes
fdupes -r /home/user
fdupes -rdN /home/user # Delete duplicates📦 12. Remove Unused Flatpak Apps
flatpak uninstall --unused✅ Like Snap, Flatpak can take up hidden space.
📁 13. Mount External Volumes Correctly
Sometimes disk full errors are due to writing to root (/) instead of a mounted path. Always check:
mount | grep <mountpoint>
df -h✅ Prevents accidental writes to the wrong disk.
🔄 14. Reboot to Release Deleted Files Still in Use
If a large file was deleted but still held open by a process:
lsof | grep deletedKill the process or reboot:
kill -9 <PID>✅ Disk space is not released until the file handle is closed.
🧾 Summary Table
Find large files
du, ncdu, find, df
✅
Clean package cache
apt clean, yum clean all
✅
Clear logs
journalctl --vacuum-*
✅
Delete temp files
rm -rf /tmp/*
✅
Clear trash
rm -rf ~/.local/share/Trash/*
✅
Uninstall unused apps
apt remove
✅
Remove old kernels
apt autoremove
✅
Clean Docker data
docker system prune
⚠️
Remove orphaned packages
deborphan
✅
Delete duplicate files
fdupes -rdN
⚠️
Remove old Snap/Flatpak revisions
snap remove, flatpak uninstall
✅
Reboot or close deleted files
`lsof
grep deleted`
Would you like a bash script to automate all safe disk cleanups?
Last updated