Who doesn’t love sports? Every year, when sports season begins, we all start rooting for our favorite teams. Now how many times has a busy schedule or an emergency at work made you miss a game, that too when your favorite team is playing? Pretty sure we all have been there. This brings us to the concept of leaderboard – a scoreboard showing the ranking or data points in a well computed manner to cope with what you have missed. What NCache does is, make your leaderboard application a lot more efficient with a distributed caching solution to achieve a magnificent performance. Let us discuss how.
What are we trying to achieve here?
So, let’s suppose you want to create an application that takes in updates live from the match venues and displays them to all the users that have subscribed to the updates. For a match that has already ended, the user gets a detailed score and results of the match. Similarly, the subscribed user also gets notified when a new match starts.
There are tons of systems providing you with this functionality, however, for a live scoring application, network glitches and delays are a big setback. Well the good news that NCache brings is that you do not need to worry about all that with NCache.
NCache uses distributed in-memory computing to give you the fastest and most optimal output for hundreds and thousands of users whether old or if they are just joining. It manages heavy traffic without choking on the performance bottlenecks causing it to slow down or crash. Moreover, it is a distributed and linearly scalable in-memory datastore, thus handling any number of client requests and ensure a reliable connection with cache client. We have created a ready to run sample application for you and made available on Github as a demonstration.
NCache Leaderboard Application: An Overview
Let us start with the overview of what the application does. The basic functionality is divided into two parts:
- Subscribed user: A user subscribed to view the live score.
- Score Update Team: A user updating the live score for the subscribed user.
Once the match begins the score update team starts making updates about the match on their APIs that provides updates to whoever has the license to receive those updates. An overall view of the application architecture is shown below:
In our system backed by NCache, the live notifications will be published to the NCache cluster servers using Cache Publish Subscribe Model where a publisher publishes a message linking to a particular topic and the subscriber that has subscribed to the topic receives an update whenever a change has been made to that topic. In our case whenever a match update will occur, it will be published and all users subscribed to the match will receive this as an update to the match score.
All subscribers to the match receive instant updates using NCache SignalR Backplane. SignalR Backplane is an NCache extension of the ASP.NET SignalR that allows efficient use of ASP.NET SignalR in a web farm while ensuring smooth flow of relevant data to each user from multiple servers. The match handler uses NCache Backing Source to read and write the cache data from and to the database. Look at the figure below to understand the working of the application:
Using Pub/Sub to Publish and Subscribe with Match Updates
Using NCache Pub/Sub’s model, the user subscribe to the topic for match updates. Whenever the score update team updates the score, a message is published and the subscribed user gets notified about the update. The subscribed user thus retrains newly updated data every time, hence the updated score.
The code given below describes how to publish a message on a specific topic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
ICache cache = CacheManager.GetCache("myPartitionedCache"); // create pub/sub topic on match start cache.MessagingService.CreateTopic(matchName); // create start update MatchUpdate start = new MatchUpdate(datetime, "match_start", "stadium", "Match has Started"); // create new Message packet with the match update Message message = new Message(start); // fetch topic handler from cache ITopic topic = _cache.MessagingService.GetTopic(matchName); // publish Message on topic topic.Publish(message, DeliveryOption.All); |
The code below shows how can a user subscribe to a specific topic
1 2 3 4 5 6 7 8 |
ITopicSubscription matchSubscription = cache.MessagingService.GetTopic(matchName).CreateSubscription(MatchUpdates); ... // Creating Callback public void MatchUpdates(object sender, MessageEventArgs args) { hub.Clients.All.SendAsync("MatchUpdate", new JsonResult((MatchUpdate)args.Message.Payload)); } |
Using SignalR Backplane to Receive updates on the Match
NCache SignalR Backplane is an extension provided by NCache to maintain persistent connections with all the users subscribed for constant updates. The best part about offering this is minimizing the constant delays and adding real time functionality to your application, hence no frustrating delays.
Look at the code below to show you NCache SignalR Backplane can be registered in your application:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Get cache name and event key from appsettings.json string cacheName = Configuration.GetValue("CacheName"); string eventKey = Configuration.GetValue("EventKey"); GlobalHost.DependencyResolver.UseNCache(cacheName, eventKey); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseSignalR(routes => { routes.MapHub("/signalr"); }); app.UseMvc(); |
Backing Source for Reading/Writing data from the Data Source
Your application needs to remain synchronized with your database so the match scores are also updated in the data source. NCache provides Data source providers that include:
- Read-Through Provider: For any updates not cached, the database is directly looked upon to fetch the updated data.
- Write Through Provider: For keeping the data source synchronized with the data source, the data is written in the cache as well as the data source, hence zero inconsistency.
Keeping the above two factors in mind look at the code below for keeping the data source synchronized with your cache.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public ScoreUpdateController(IConfiguration configuration) { // get cache name from appsettings.json string cacheName = configuration.GetValue("CacheName"); // get read/write thru provider name from appsettings.json string readThruProviderName = configuration.GetValue("ReadThruProviderName"); string writeThruProviderName = configuration.GetValue("WriteThruProviderName"); // initialize store match handler if not initialized before if (storeHandler == null) storeHandler = new StoreHandler(cacheName, readThruProviderName, writeThruProviderName); // acquire cache handler cache = CacheManager.GetCache(configuration.GetValue("CacheName")); } |
The code below shows fetching updates with read-through enabled and writing the updated data to cache as well as data store.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public void SaveUpdates(string matchName, MatchUpdate matchUpdate) { // fetch list handler from cache IDistributedList distributedList = cache.DataTypeManager.GetList(matchName, readThruOptions); // if there is no list initialized, create new list with writethru enabled if (distributedList == null) { distributedList = cache.DataTypeManager.CreateList(matchName, null, writeThruOptions); } // add new update to list distributedList.Add(matchUpdate); |
To Sum It All Up…
We just learned how to make a live scoreboard application using NCache that can accommodate a huge number of users streaming the match live without any glitches or inconsistencies. How cool is that? Gone are the days when a goal would be shown minutes after it actually happened. Now you can enjoy your favorite game on the go!
So, which team are you rooting for? Also! Don’t forget to check out our other very interesting features and use cases, NCache never disappoints.
Digital scoreboards play a crucial role in providing real-time updates and information to sports fans. In the context of a live scoring application, having an efficient and reliable system is paramount. NCache offers a distributed caching solution that ensures optimal performance and scalability for handling a large number of users and their requests. By leveraging distributed in-memory computing, NCache minimizes network glitches and delays, providing a seamless experience for users. The importance of a well-functioning digital scoreboard cannot be overstated, and solutions like NCache contribute to enhancing the overall experience of sports enthusiasts.