Caching is the process of temporarily holding the most frequently queried data in transient memory. This reduces data load time as well as providing ease of access to the database.

Application developers usually use a 3-tier architecture in the creation of usable and adjustable applications. The tier includes a presentation layer (user interface), an application layer (business logic), and a data layer (databases and file storage).

  • Presentation Layer: this is the interface that users interact with. It translates tasks and results from machine readable to human readable making the user to understand what’s going on.
  • Application Layer: processes commands, makes logical decisions and processes data between the user interface and the database.
  • Data Layer: this is the actual storage location for both data and files.

These layers are able to work and be maintained independently, and frequently be set up in separate hosts. For every data query, the application makes, its speed is limited by network performance. Data retrieval plays a crucial role in user experience and is a vital requirement in most commercial applications.

What is Memcached?

Memcached is a free & open-source, distributed memory object caching system that’s generic in nature, used to speed up dynamic web applications by reducing database load. It stores data in memory, based on a key-value pair. 

Memcached ease of use, fast deployment, and an API that is widely available on favored programming languages e.g., python, PHP, java among others.

Installation of Memcached on Debian 10 (Buster)

This guide will be taking you through the installation and configuration of Memcached on the Debian 10 Operating System. Debian 10 repository already has Memcached packages installed making it easier for us to use the APT package manager to install it.

We start by updating the system packages, as displayed below:

sudo apt update
sudo apt full-upgrade

Once done we install Memcached by running the following command:

$ sudo apt install memcached
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  libevent-2.1-6 libmemcached11 libmemcachedutil2
Suggested packages:
  libcache-memcached-perl libmemcached libanyevent-perl libyaml-perl libterm-readkey-perl
The following NEW packages will be installed:
  libevent-2.1-6 libmemcached-tools libmemcached11 libmemcachedutil2 memcached
0 upgraded, 5 newly installed, 0 to remove and 12 not upgraded.
Need to get 502 kB of archives.
After this operation, 1364 kB of additional disk space will be used.
Do you want to continue? [Y/n] y

To verify its installation, run the command below:

● memcached.service - memcached daemon
   Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2021-06-29 18:05:40 EAT; 1min 4s ago
     Docs: man:memcached(1)
 Main PID: 127995 (memcached)
    Tasks: 10 (limit: 2325)
   Memory: 3.4M
   CGroup: /system.slice/memcached.service
           └─127995 /usr/bin/memcached -m 64 -p 11211 -u memcache -l 127.0.0.1 -P /var/run/memcached/memcached.pid

Jun 29 18:05:40 sornaqube systemd[1]: Started memcached daemon.
Jun 29 18:05:41 sornaqube systemd[1]: /lib/systemd/system/memcached.service:13: PIDFile= references path below legacy directory /var/run/, updating /v

Memcached configuration on Debian 10 (Buster)

To configure Memcached we edit Memcached configuration file, /etc/memcached.conf. However, the majority of users stick to Memcached default settings, without tweaking the configuration file Memcached listens on the localhost. A localhost connection does not require any configuration to be made on the server.

We can modify the Memcached configuration by running;

$ sudo vim /etc/memcached.conf

In the file below, locate localhost IP 127.0.0.1. replace it with your actual server IP.

# memcached default config file
# 2003 - Jay Bonci <[email protected]>
# This configuration file is read by the start-memcached script provided as
# part of the Debian GNU/Linux distribution.

# Run memcached as a daemon. This command is implied, and is not needed for the
# daemon to run. See the README.Debian that comes with this package for more
# information.
-d

# Log memcached's output to /var/log/memcached
logfile /var/log/memcached.log

# Be verbose
# -v

# Be even more verbose (print client commands as well)
# -vv

# Start with a cap of 64 megs of memory. It's reasonable, and the daemon default
# Note that the daemon will grow to this size, but does not start out holding this much
# memory
-m 64

# Default connection port is 11211
-p 11211

# Run the daemon as root. The start-memcached will default to running as root if no
# -u command is present in this config file
-u memcache

# Specify which IP address to listen on. The default is to listen on all IP addresses
# This parameter is one of the only security measures that memcached has, so make sure
# it's listening on a firewalled interface.
-l 127.0.0.1

# Limit the number of simultaneous incoming connections. The daemon default is 1024
# -c 1024

# Lock down all paged memory. Consult with the README and homepage before you do this
# -k

# Return error when memory is exhausted (rather than removing items)
# -M

# Maximize core file limit
# -r

# Use a pidfile
-P /var/run/memcached/memcached.pid

For remote connections to the server, an extra configuration is required. We will need to append the firewall to allow UDP port 11211 to be listened to by Memcached.   e will have to allow the port on the firewall by running this command.

sudo ufw allow from 0.0.0.0 to any port 11211
sudo ufw reload

Next, we are going to install Memcached additional tools with help of the command below.

sudo apt install libmemcached-tools

Memcached is now installed and well configured. We are going to test with a simple PHP script running on an Apache webserver. If you do not have PHP and Apache installed, run this command to install.

sudo apt install apache2 php libapache2-mod-php

On the screen output below, select Y then press Enter to continue.

The following NEW packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libapache2-mod-php libapache2-mod-php7.3 libapr1 libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap libbrotli1 libcurl4 libjansson4 liblua5.2-0
  libsodium23 php php-common php7.3 php7.3-cli php7.3-common php7.3-json php7.3-opcache php7.3-readline psmisc ssl-cert
0 upgraded, 25 newly installed, 0 to remove and 0 not upgraded.
Need to get 7,268 kB of archives.
After this operation, 28.3 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

We now install Memcached PHP Extension by running the command.

sudo apt install php-memcached

When Memcached is installed, it integrates itself with phpinfo file. This helps in checking and verifying that is recognized by the webserver. To see this information, create phpinfo.php file in /var/www/html.

$ sudo /var/www/html/phpinfo.php

Add lines below in the file.

<?php
// Show all information, defaults to INFO_ALL
phpinfo();

Load the file in the browser. Replace 127.0.0.1 with your server IP.

HTTP://127.0.0.1/phpinfo.php

When you scroll down the page you should be able to see Memcached information indicated as one below.

Testing of Memcached on Debian 10 (Buster)

We are going to create a simple PHP script to carry a test to see how Memcached is used in caching data and pages in Debian 10. Create a PHP file in apache root, /var/www/html/

sudo vim /var/www/html/test.php

Copy and paste the lines below in the file. Remember to replace 127.0.0.1 with your actual server IP.

<?php
$mc = new Memcached();
$mc->addServer("127.0.0.1", 11211);
 
$result = $mc->get("test_key");
 
if($result) {
        echo $result;
} else {
        echo "No cached data was found. Please refresh page to reload";
        $mc->set("test_key", "Memcached has successfully cached data!!") or die ("Failed to save data at Memcached server");
}
?>

After editing the file, save and exit.

Restart Apache and Memcached to allow changes to take effect.

sudo systemctl restart memcached
sudo systemctl restart apache2

To test via web browser, enter your server_IP or domain in browser with port 11211 in which Memcached is running. Replace 127.0.0.1 with your actual server_IP if you are running from a cloud server

HTTP://127.0.0.1/test.php

The screen below will appear. Since it is the first time you are loading the script, has not been cached hence message below will display on your screen.

When you refresh the page, Memcached will have cached the page and will be loaded from the Memcached server instead. You should be able to see a page similar to the one below.

The above two illustrations show how Memcached can be used in real-world production. Memcached has logs statistics running in the background which can be viewed by running commands below in the terminal. First run telnet command to port 1121, in which Memcached is listening.

$ telnet <localhost/server_IP>

Trying 62.12.115.67...
Connected to 62.12.115.67.
Escape character is '^]'.

In the screen output run the stats command to list the history of Memcached. You should be able to see output similar to one down here.

$ stats

#Output

STAT pid 128695
STAT uptime 622738
STAT time 1625602056
STAT version 1.5.6
STAT libevent 2.1.8-stable
STAT pointer_size 64
STAT rusage_user 82.657987
STAT rusage_system 74.395967
STAT max_connections 1024
STAT curr_connections 2
STAT total_connections 278
STAT rejected_connections 0
STAT connection_structures 3
STAT reserved_fds 20
STAT cmd_get 273
STAT cmd_set 2
STAT cmd_flush 2
STAT cmd_touch 0
STAT get_hits 271
STAT get_misses 2
STAT get_expired 0
STAT get_flushed 0
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 0
STAT incr_hits 0
STAT decr_misses 0
STAT decr_hits 0
STAT cas_misses 0
STAT cas_hits 0
STAT cas_badval 0
STAT touch_hits 0
STAT touch_misses 0
STAT auth_cmds 0
STAT auth_errors 0
STAT bytes_read 6857
STAT bytes_written 20005
STAT limit_maxbytes 67108864
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT time_in_listen_disabled_us 0
STAT threads 4
STAT conn_yields 0
STAT hash_power_level 16
STAT hash_bytes 524288
STAT hash_is_expanding 0
STAT slab_reassign_rescues 0
STAT slab_reassign_chunk_rescues 0
STAT slab_reassign_evictions_nomem 0
STAT slab_reassign_inline_reclaim 0
STAT slab_reassign_busy_items 0
STAT slab_reassign_busy_deletes 0
STAT slab_reassign_running 0
STAT slabs_moved 0
STAT lru_crawler_running 0
STAT lru_crawler_starts 51765
STAT lru_maintainer_juggles 1865386
STAT malloc_fails 0
STAT log_worker_dropped 0
STAT log_worker_written 0
STAT log_watcher_skipped 0
STAT log_watcher_sent 0
STAT bytes 0
STAT curr_items 0
STAT total_items 2
STAT slab_global_page_pool 0
STAT expired_unfetched 0
STAT evicted_unfetched 0
STAT evicted_active 0
STAT evictions 0
STAT reclaimed 2
STAT crawler_reclaimed 0
STAT crawler_items_checked 0
STAT lrutail_reflocked 408
STAT moves_to_cold 259
STAT moves_to_warm 257
STAT moves_within_lru 4
STAT direct_reclaims 0
STAT lru_bumps_dropped 0

You clear Memcached to empty storage with the below command.

sudo flush_all

Use quit command to exit telnet.

$ quit

Conclusion

Just like any other caching mechanism, Memcached can store data and load it next time the client requests the same page. This helps in reducing server workloads, loading one page simultaneously. Throughout the guide, we were able to install Memcached and configure. We have also looked into how Memcached can be used in the real world by running a sample PHP script. I believe the guide was helpful and should you have queries leave a comment.

Other people also read on;

Install TaskBoard on CentOS Stream 8 | Rocky Linux 8

How To Run VS Code in browser secured with Let’s Encrypt

Setup CTparental Parental Control Software on Ubuntu

LEAVE A REPLY

Please enter your comment!
Please enter your name here