x_maras
x_maras

Reputation: 2217

Having a local and a remote client with Redis

I want to set some write constraints in Redis and I was thinking to store these constraints in hashes.

My initial idea was to modify the set commands so they check the rules before they write in Redis. I was thinking that by this way the check would be super fast. Of course such an approach would demand more modifications every time that Redis is changed, which I find a little bit hardcore if you think that it is about a school assignment.

The second idea is that there are 2 types of Redis clients. One in the web application side (might be several instances of the web application) and one on the Redis machine. Based on this idea come my questions.

  1. Would the 2 clients (local and remote) have increased performance in comparisson to 1 client that first checks the constraints and then writes in Redis? Or should I stick to the one client that does it all (phpredis or predis, the application is on PHP, with some modifications for the constraints check)?

  2. If I could try the 2 clients, in which programming language would be better to be implemented the local client (C, Lua or other)?

Upvotes: 2

Views: 1029

Answers (1)

Didier Spezia
Didier Spezia

Reputation: 73306

Rather than trying to modify Redis behavior itself, I would try first to implement the constraints in server-side Lua scripts (Redis 2.6 branch required).

A Lua EVAL script can easily perform some checks with the data already stored in Redis before doing the actual write operation.

Here is an example. Suppose we have two keys representing bank accounts and we need to implement a safe transaction between accounts. For instance, we have to check that both accounts exist and the source account contains the required funds.

# set 2 accounts for John and Bob
set account:john 100
set account:bob 20

# transfer $10 from John to Bob, checking all constraints
eval "if redis.call('exists',KEYS[2])==1 and redis.call('get',KEYS[1])>=ARGV[1] then
         redis.call( 'incrby', KEYS[2], ARGV[1] )
         redis.call( 'incrby', KEYS[1], - ARGV[1] )
         return 1
      else
         error('invalid transaction')
      end" 2 account:john account:bob 10

You will find documentation about Redis scripting capabilities at: http://redis.io/commands#scripting (see the EVAL command first).

To answer your initial question (and if you cannot use Redis 2.6), a local client would slightly improve the performance since it can connect to Redis using unix domain sockets (bypassing some TCP overhead) and save some network roundtrips. But this is at the price of extra complexity.

Upvotes: 2

Related Questions