Flushing All Memcached Data in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

Flushing all data from a Memcached instance is often required during testing or when you want to clear the cache completely. This might be necessary in scenarios such as changing application behavior, reconfiguring data storage settings, or cleaning up after specific processes.

Code Examples

We use the flush method provided by the 'memjs' node package to flush all the data in a Memcached instance. First, make sure to install it via npm install memjs.

var memjs = require('memjs') var mc = memjs.Client.create() mc.flush(function(err) { if (err) console.error("Error flushing:", err) else console.log("Flushed all keys successfully") })

This example connects to a Memcached server and calls the flush function. If there's an error, it will log that error; otherwise, it will log a successful flush message.

Ensure your Memcached server is running and accessible, otherwise, this will throw a connection error.

Best Practices

  • Only use flush sparingly, as it wipes out all data in Memcached. It's not recommended for routine use but can be very useful in development or testing environments.
  • Always handle errors returned from flush method to avoid unhandled exceptions in your Node.js application.

Common Mistakes

  • Not handling the error in the callback function of flush. If there's an issue with the network or the Memcached server, it will return an error which should be properly handled.
  • Using flush in a production environment without understanding its implications. It completely wipes out all cached data, which could potentially impact the performance of your application if used inappropriately.


  1. What does 'flush' do in Memcached? The 'flush' command in Memcached invalidates all existing cache items immediately, freeing up all the memory that was used by these items.

  2. Can I recover data after flushing Memcached? No, once data is flushed from Memcached it cannot be recovered. It's a destructive operation.

  3. Does 'flush' stop the Memcached server? No, the 'flush' operation only clears the cache and does not stop or restart the Memcached server.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.