8

I like the Lua-scripting for redis but i have a big problem with TIME.

I store events in a SortedSet.

The score is the time, so that in my application i can view all events in given time-window.

redis.call('zadd', myEventsSet, TIME, EventID);

Ok, but this is not working - i can not access the TIME (Servertime).

Is there any way to get a time from the Server without passing it as an argument to my lua-script? Or is passing the time as argument the best way to do it?

Thomas Deutsch
  • 2,344
  • 2
  • 27
  • 36
  • 1
    meanwhile there is TIME. With some lua you can wrap that around zadd. `127.0.0.1:6379> eval "local t = (redis.call('time')); return t[1]" 0 "1438894559"` – Markus Aug 06 '15 at 20:42

1 Answers1

13

This is explicitly forbidden (as far as I remember). The reasoning behind this is that your lua functions must be deterministic and depend only on their arguments. What if this Lua call gets replicated to a slave with different system time?

Edit (by Linus G Thiel): This is correct. From the redis EVAL docs:

Scripts as pure functions

A very important part of scripting is writing scripts that are pure functions. Scripts executed in a Redis instance are replicated on slaves by sending the script -- not the resulting commands.

[...]

In order to enforce this behavior in scripts Redis does the following:

  • Lua does not export commands to access the system time or other external state.
  • Redis will block the script with an error if a script calls a Redis command able to alter the data set after a Redis random command like RANDOMKEY, SRANDMEMBER, TIME. This means that if a script is read-only and does not modify the data set it is free to call those commands. Note that a random command does not necessarily mean a command that uses random numbers: any non-deterministic command is considered a random command (the best example in this regard is the TIME command).

There is a wealth of information on why this is, how to deal with this in different scenarios, and what Lua libraries are available to scripts. I recommend you read the whole documentation!

Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367