Redis only supports a handful of data types. Our data model has to fit within them. Are we crazy for trying this? It’s time to think about the data model for Request Metrics. We plan to store all customer records in Redis. This requires some thought because Redis is not a relational database. Any linkages between entities like users and customers must be managed by us. The data model should be full enough that we can find the the linkages we need, but not so complex that we continually break the linkages or need complex cleanup operations.
The first thing we need is a user. We’d like to work on authentication soon and we won’t get far without a user to login with. But first, our usage of StackExchange.Redis needs improvement.
Using the StackExchange.Redis Connection Multiplexer
In our first tests of Redis in .NET Core, we played fast and loose to complete an end to end test as quickly as possible. This was at the expense of mis-using the Redis Connection Multiplexer.
The ConnectionMultiplexer must be a singleton that is re-used for the lifetime of your application. It handles disconnects and connection pooling internally. The multiplexer behaves badly if it is re-built for every call so we use a helper to handle the multiplexer for us:
Using Redis Hash Sets
Each user object is JSON encoded into its own field stored in a single “users” Redis HashSet. This has two advantages. First, the total number of redis keys is reduced. Second, the hashset gives an easy way to fetch all users that doesn’t depend on Redis key scans.
Let’s explore basic HashSet CRUD. We use async calls because the StackExchange.Redis authors seem to prefer them:
Delete All Redis Data
Early on in development we need to clear the Redis store a lot as we refine the data model. We can do this programatically:
Redis has many more datatypes that we’ll surely use soon. For now, Redis hash sets provide a nice way to group together similar data like our user records. Next time we’ll take our user records and implement simple, cookie based authentication in our ASP.NET Core application.
Request Metrics is drop-in application monitoring where it matters most:
the end user experience. From API Observability to User Sessions,
developers can see the problems that matter to users, fix them faster,
and continuously improve their applications. Request Metrics provides
software observability in minutes instead of months for companies worldwide like
eBay, Virgin Mobile, and Aljazeera.