...

Out of Sight but Never Out of Mind

Amid the digital pulse, where data weaves through the matrix, lies a world unseen yet
palpably powerful. Enter the enigmatic domain of out-of-process caching—a preservation of
effort. Like a mint figurine of your favourite super action hero preserved with original packaging!
In this concealed sanctuary, technology doesn't just function; it performs. Redis, the high-
performance in-memory data structure store that has revolutionized the art of caching. Data
flutters like whispers, nestled beyond the obvious paths, always poised, never dormant. It's the
unsung hero of seamless experiences, the backstage virtuoso ensuring that your queries and
commands meet with no delay.
Redis stands at the heart of this covert operation. Its ultra-fast data access capabilities
transform it into the secret haven for your most crucial data. The elegance of Redis lies in its
ability to store data in memory, enabling rapid retrieval and reducing latency. From real-time
analytics to session management, Redis effortlessly handles the heavy lifting, providing a swift
and reliable caching solution.
Redis is a maestro conducting an intricate performance, where every element plays a pivotal
role. At the heart of Redis's magic are its versatile data structures—from simple strings to
complex sorted sets, each designed to handle a unique aspect of data management. Imagine
an efficient queue with lists, a precise ranking system with sorted sets, or a compact object
with hashes.
Add to it its persistence mechanisms, RDB snapshots, and Append-Only Files (AOF) ensure
that data remains secure, even in the face of server crashes. With master-slave replication,
Redis provides redundancy and high availability, ensuring that data is always within reach.
Redis's capability extends into the realm of real-time messaging with its pub/sub system,
allowing messages to be broadcast effortlessly to multiple subscribers. With transactions, Redis
guarantees atomic execution, ensuring data integrity with every operation.
Bootstrapping
We will skip the customary installation and testing of the installation. Redis has sufficiently well
documented articles for this purpose. Let us get cracking with the CLI and perform some basic
operations.
Basic operations
SET preferred_name "Santa Banta"

GET preferred_name
This is fairly simple where we store a piece of data (datum) in redis only to retrieve it latter. Let
us do something more interesting.
INCR items_in_cart
Here we are incrementing a number by 1. Let us increase the level of interest by working with a
list.

LPUSH cart_items "Teamware blog collections"
LPUSH cart_items "Technical debt, what is it?"
Here we are pushing strings (title of popular books) into cache for quick data retrieval workflow
in the checkout.
Extending it we can fetch a value using
LRANGE cart_items 0 -1
We are picking the first element from the list it runs till the end since we are using negative
index in the last element.
Weaving cache in application
Using python let us look at how we would weave it into an application. We will use the redis
official python package. Like earlier we will skip the installation and get right away to the code.
import redis
client = redis.Redis(host='localhost', port=6379, db=0)
client.set(‘preferred_name’, ‘Santa banta’)
value = client.get(‘preferred_name’)
print(value.decode('utf-8'))
client.incr(‘items_in_cart’)
client.lpush(‘cart_items’, ‘Teamware blog collections’)
client.lpush(‘cart_items’, ‘Technical debt, what is it?’)

values = client.lrange('mylist', 0, -1)
for val in values:
print(val.decode('utf-8'))
We do not think we need to explain what is happening in the code snippet above. It is kind of
giving away, isn’t it? A hallmark quality of a library will be how close its API signature is across
platform, and modes of consumption. Redis library in that manner is outstanding with python
library and CLI.
We have so far seen the capability in isolation. It is like writing hello world. We now show how it
can serve a purpose.
from flask import Flask, request, jsonify
import redis
import json

app = Flask(__name__)
cache = redis.Redis(host='localhost', port=6379, db=0)
database = {
"product_1": {"name": "Product 1", "price": 100, "stock": 50},
"product_2": {"name": "Product 2", "price": 150, "stock": 30},
# More products…
}
def get_product_from_db(product_id):
return database.get(product_id)
def get_product(product_id):
product = cache.get(product_id)
if product:
return json.loads(product)
product = get_product_from_db(product_id)
if product:

cache.set(product_id, json.dumps(product), ex=3600) # Cache for 1 hour
return product
In this code we set up a dummy product database in-memory. In reality this will be a database
over the network carrying the baggage of network latency. The crux of using cache lies in
checking if the data is available in cache before hitting the database. With cache it is out of
memory yet faster than a network call. You could also drop it in a remote server. Making call to
database and far-away cache have equivalence. However, we can assure you it will be still
faster. How? That is a topic for next dispatch

 

#Redis #PerformantSoftware #Python #Caching

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.