Skip to content

Commit 8cb87fe

Browse files
committed
897352: Adding UG for Redis
1 parent 929b63e commit 8cb87fe

File tree

5 files changed

+166
-103
lines changed

5 files changed

+166
-103
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
layout: post
3+
title: Collaborative Editing in ##Platform_Name## Document Editor Control | Syncfusion
4+
component: DocumentEditor
5+
description: Learn about collaborative editing in Syncfusion ##Platform_Name## Document editor control of Syncfusion Essential JS 2 and more.
6+
publishingplatform: ##Platform_Name##
7+
documentation: ug
8+
domainurl: ##DomainURL##
9+
---
10+
11+
# Collaborative Editing
12+
13+
Allows multiple users to work on the same document simultaneously. This can be done in real-time, so that collaborators can see the changes as they are made. Collaborative editing can be a great way to improve efficiency, as it allows team members to work together on a document without having to wait for others to finish their changes.
14+
15+
## Prerequisites
16+
17+
- *Real-time Transport Protocol*: This protocol facilitates instant communication between clients and the server, ensuring immediate updates during collaborative editing.
18+
- *Distributed Cache or Database*: Used to temporarily store the queue of editing operations.
19+
20+
### Real time transport protocol
21+
22+
- *Managing Connections*: Keeps active connections open for real-time collaboration, allowing seamless communication between users and the server.
23+
- *Broadcasting Changes*: Ensures that any edits made by one user are instantly sent to all collaborators, keeping everyone on the same page with the latest document version.
24+
25+
### Distributed cache or database
26+
27+
To support collaborative editing, it's crucial to have a backing system that temporarily stores the editing operations of all active users. There are two primary options:
28+
29+
- *Distributed Cache*: Handles a higher number of `HTTP` requests per second compared to a database approach. For instance, a server with 2 vCPUs and 8GB RAM can handle up to 125 requests per second using a distributed cache.
30+
- *Database*: With the same server configuration, it can handle up to 50 requests per second.
31+
32+
Using the distributed cache or database all the editing operations are queued in order and conflict resolution is performed using `Operational Transformation` Algorithm.
33+
34+
> *Recommendation* - If you expect average `http` requests per second of your live application as 50 or below, then the database can provide reliable a backing system for operation queue. If you expect average requests per second of your live application as above 50, then the distributed cache is highly recommended backing system.
35+
> Tips to calculate the average requests per second of your application:
36+
Assume the editor in your live application is actively used by 1000 users and each user's edit can trigger 2 to 5 requests per second. The total requests per second of your applications will be around 2000 to 5000. In this case, you can finalize a configuration to support around 5000 average requests per second.
37+
38+
> Note: The above metrics are based solely on the collaborative editing module. Actual throughput may decrease depending on other server-side interactions, such as document importing, pasting formatted content, editing restrictions, and spell checking. Therefore, it is advisable to monitor your app's traffic and choose a configuration that best suits your needs.
39+
#### See Also
40+
41+
- [Collaborative editing using Redis cache in ASP.NET Core](../../document-editor/collaborative-editing/using-distributed-cache-asp-net-core)
42+
- [Collaborative editing using Microsoft SQL server in ASP.NET Core](../../document-editor/collaborative-editing/using-database-in-asp-net-core)
43+
- [Collaborative editing using Java](../../document-editor/collaborative-editing/using-java)

ej2-asp-core-mvc/document-editor/collaborative-editing/using-redis-in-asp-net.md renamed to ej2-asp-core-mvc/document-editor/collaborative-editing/using-redis-cache-asp-net.md

Lines changed: 117 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
---
2+
layout: post
23
title: Collaborative Editing in ##Platform_Name## Document Editor Control | Syncfusion
34
component: DocumentEditor
45
description: Learn how to enable and perform collaborative editing in Syncfusion ##Platform_Name## Document editor.
56
publishingplatform: ##Platform_Name##
7+
documentation: ug
8+
domainurl: ##DomainURL##
69
---
710

811
# Collaborative Editing
@@ -14,7 +17,64 @@ Allows multiple users to work on the same document simultaneously. This can be d
1417
Following things are needed to enable collaborative editing in Document Editor
1518

1619
- SignalR
17-
- Redis cache
20+
- Redis
21+
22+
## SignalR
23+
24+
In collaborative editing, real-time communication is essential for users to see each other's changes instantly. We use a real-time transport protocol to efficiently send and receive data as edits occur. For this, we utilize SignalR, which supports real-time data exchange between the client and server. SignalR ensures that updates are transmitted immediately, allowing seamless collaboration by handling the complexities of connection management and offering reliable communication channels.
25+
26+
To make SignalR work in a distributed environment (with more than one server instance), it needs to be configured with either Azure SignalR Service or a Redis backplane.
27+
28+
### Scale-out SignalR using Azure SignalR service
29+
30+
Azure SignalR Service is a scalable, managed service for real-time communication in web applications. It enables real-time messaging between web clients (browsers) and your server-side application(across multiple servers).
31+
32+
Below is a code snippet to configure Azure SignalR in an ASP.NET Core application using the ```AddAzureSignalR``` method
33+
34+
```csharp
35+
builder.Services.AddSignalR() .AddAzureSignalR("<your-azure-signalr-service-connection-string>", options => {
36+
// Specify the channel name
37+
options.Channels.Add("document-editor");
38+
});
39+
```
40+
41+
### Scale-out SignalR using Redis
42+
43+
Using a Redis backplane, you can achieve horizontal scaling of your SignalR application. The SignalR leverages Redis to efficiently broadcast messages across multiple servers. This allows your application to handle large user bases with minimal latency.
44+
45+
In the SignalR app, install the following NuGet package:
46+
* ` Microsoft.AspNetCore.SignalR.StackExchangeRedis`
47+
48+
Below is a code snippet to configure Redis backplane in an ASP.NET Core application using the ```AddStackExchangeRedis ``` method
49+
50+
```csharp
51+
builder.Services.AddSignalR().AddStackExchangeRedis("<your_redis_connection_string>");
52+
```
53+
Configure options as needed:
54+
55+
The following example shows how to add a channel prefix in the ConfigurationOptions object.
56+
57+
```csharp
58+
builder.Services.AddDistributedMemoryCache().AddSignalR().AddStackExchangeRedis(connectionString, options =>
59+
{
60+
options.Configuration.ChannelPrefix = "document-editor";
61+
});
62+
```
63+
64+
## Redis
65+
66+
In collaborative editing, Redis is used to store temporary data that helps queue editing operations and resolve conflicts using the `Operational Transformation` algorithm.
67+
68+
All editing operations in collaborative editing are stored in the Redis cache. To prevent memory buildup, we can configure a `SaveThreshold` limit at the application level. If the `SaveThreshold` is 100, editing operations up to twice the save threshold limit are kept in Redis per document. Once exceeded, the first 100 operations (as defined by the save threshold) are removed from the cache and automatically saved to the source input document.
69+
70+
The configuration and store size of the Redis cache can be adjusted based on the following considerations.
71+
72+
- *Storage Requirements*: A minimum of 400KB of cache memory is needed for editing a single document, with the capacity to store up to 100 editing operations. Storage needs may increase based on following factor.
73+
- *Images*: Increases with the number of images added to the document.
74+
- *Pasted content*: Depends on the size of the SFDT content.
75+
- *Connection Limits*: Redis has a limit on concurrent connections. Choose the Redis configuration based on your user base to ensure optimal performance.
76+
77+
> For better performance, we recommend to have minimum `SaveThreshold` limit of 100.
1878
1979
## How to enable collaborative editing in client side
2080

@@ -202,14 +262,14 @@ CollaborativeEditingController.UpdateOperationsToSourceDocument(roomName, “<<d
202262

203263
```
204264

205-
### Step 3: Configure Redis connection string in application level
265+
### Step 3: Configure Redis cache connection string in application level
206266

207267
Configure the Redis that stores temporary data for the collaborative editing session. Provide the Redis connection string in `appsettings.json` file.
208268

209269
```json
210270
.....
211271
"ConnectionStrings": {
212-
"Redis": "<Redis connection string>"
272+
"RedisConnectionString": "<<Your Redis connection string>>"
213273
}
214274
.....
215275

@@ -219,8 +279,8 @@ Configure the Redis that stores temporary data for the collaborative editing ses
219279

220280
#### Import File
221281

222-
1. When opening a document, check the redis list for pending operations and get them for the collaborative editing session.
223-
2. If the pending operations already exists, apply them to the WordDocument instance using the `UpdateActions` method before converting it to the SFDT format.
282+
1. When opening a document, check the Redis cache for pending operations and retrieve them for the collaborative editing session.
283+
2. If pending operations exist, apply them to the WordDocument instance using the `UpdateActions` method before converting it to the SFDT format.
224284

225285
```csharp
226286
public string ImportFile([FromBody] FileInfo param)
@@ -246,23 +306,15 @@ public string ImportFile([FromBody] FileInfo param)
246306
return Newtonsoft.Json.JsonConvert.SerializeObject(content);
247307
}
248308

249-
public async Task<List<ActionInfo>> GetPendingOperations(string listKey, long startIndex, long endIndex)
250-
{
251-
// Get the database connection from the Redis connection multiplexer
252-
var db = _redisConnection.GetDatabase();
253-
// Fetch the list of operations from Redis using the provided key and index range
254-
var values = await db.ListRangeAsync(listKey, startIndex, endIndex);
255-
// Deserialize the operations from JSON to ActionInfo objects and return as a list
256-
return values.Select(value => Newtonsoft.Json.JsonConvert.DeserializeObject<ActionInfo>(value)).ToList();
257-
}
258-
259309
```
260310

261-
#### Update editing operations to redis.
311+
#### Update editing records to Redis cache.
312+
313+
Each edit operation made by the user is sent to the server and pushed into a Redis list data structure. Each operation is assigned a version number upon insertion into Redis.
262314

263-
Each edit operation made by the user is sent to the server and is pushed into the redis list data structure. Each operation receives a version number after being inserted into the redis.
264-
After inserting the records to the server, the position of the current editing operation must be transformed against any previous editing operations not yet synced with the client using the TransformOperation method.
265-
After performing the transformation, the current operation is broadcast to all connected users within the group.
315+
After inserting the records to the server, the position of the current editing operation must be transformed relative to any previous editing operations not yet synced with the client using the `TransformOperation` method to resolve any potential conflicts with the help of the `Operational Transformation` algorithm.
316+
317+
Once the conflict is resolved, the current operation is broadcast to all connected users within the group.
266318

267319
```csharp
268320
public async Task<ActionInfo> UpdateAction([FromBody] ActionInfo param)
@@ -283,56 +335,21 @@ public async Task<ActionInfo> UpdateAction([FromBody] ActionInfo param)
283335
private ActionInfo AddOperationsToTable(ActionInfo action)
284336
{
285337
int clientVersion = action.Version;
338+
string insertScript = "-------"
286339
…………
287340
…………
288341
…………
289342
…………
290-
List<ActionInfo> previousOperations = ((RedisResult[])results[1]).Select(value => JsonConvert.DeserializeObject<ActionInfo>(value.ToString())).ToList();
291-
previousOperations.ForEach(op => op.Version = ++clientVersion);
292-
if (previousOperations.Count > 1)
293-
{
294-
// Set the current action to the last operation in the list
295-
action = previousOperations.Last();
296-
// Transform operations that have not been transformed yet
297-
previousOperations.Where(op => !op.IsTransformed).ToList().ForEach(op => CollaborativeEditingHandler.TransformOperation(op, previousOperations));
298-
}
299-
action = actions[actions.Count - 1];
300-
action.Version = updateVersion;
301-
//Return the transformed operation to broadcast it to other clients.
302-
return action;
303-
}
304-
305-
```
306343

307-
#### Add Web API to get previous operation as a backup to get lost operations
344+
IDatabase database = _redisConnection.GetDatabase();
345+
// Define the keys for Redis operations based on the action's room name
346+
RedisKey[] keys = new RedisKey[] { action.RoomName + CollaborativeEditingHelper.VersionSuffix, action.RoomName, action.RoomName + CollaborativeEditingHelper.RevisionSuffix };
347+
// Serialize the action and prepare values for the Redis script
348+
RedisValue[] values = new RedisValue[] { JsonConvert.SerializeObject(action), clientVersion.ToString(), CollaborativeEditingHelper.SaveThreshold.ToString() };
349+
// Execute the Lua script in Redis and store the results
350+
RedisResult[] results = (RedisResult[])await database.ScriptEvaluateAsync(insertScript, keys, values);
308351

309-
On the client side, messages broadcast using SignalR may be received in a different order, or some operations may be missed due to network issues. In these cases, we need a backup method to retrieve missing operations from the redis.
310-
Using the following method, we can retrieve all operations after the last successful client-synced version and return all missing operations to the requesting client.
311-
312-
```csharp
313-
public async Task<ActionInfo> UpdateAction([FromBody] ActionInfo param)
314-
{
315-
try
316-
{
317-
ActionInfo modifiedAction = AddOperationsToTable(param);
318-
//After transformation broadcast changes to all users in the group
319-
await _hubContext.Clients.Group(param.RoomName).SendAsync("dataReceived", "action", modifiedAction);
320-
return modifiedAction;
321-
}
322-
catch
323-
{
324-
return null;
325-
}
326-
}
327-
328-
private ActionInfo AddOperationsToTable(ActionInfo action)
329-
{
330-
int clientVersion = action.Version;
331-
…………
332-
…………
333-
…………
334-
…………
335-
List<ActionInfo> previousOperations = ((RedisResult[])results[1]).Select(value => JsonConvert.DeserializeObject<ActionInfo>(value.ToString())).ToList();
352+
List<ActionInfo> previousOperations = ((RedisResult[])results[1]).Select(value => JsonConvert.DeserializeObject<ActionInfo>(value.ToString())).ToList();
336353
previousOperations.ForEach(op => op.Version = ++clientVersion);
337354
if (previousOperations.Count > 1)
338355
{
@@ -348,46 +365,49 @@ private ActionInfo AddOperationsToTable(ActionInfo action)
348365
}
349366

350367
```
351-
## How to perform Scaling in Collaborative Editing.
352368

353-
As the number of user increases, maintaining responsiveness and performance becomes challenging. Scaling tackles this by distributing the workload across resources. You can scale the collaborative editing application using either ```Azure SignalR service or Redis backplane service```
354-
355-
### 1. Scaling with Azure SignalR
356-
357-
Azure SignalR Service is a scalable, managed service for real-time communication in web applications. It enables real-time messaging between web clients (browsers) and your server-side application(across multiple servers).
358-
359-
Below is a code snippet to configure Azure SignalR in an ASP.NET Core application using the ```AddAzureSignalR``` method
360-
361-
```csharp
362-
builder.Services.AddSignalR() .AddAzureSignalR("<your-connection-string>", options => {
363-
// Specify the channel name
364-
options.Channels.Add("document-editor");
365-
});
366-
```
367-
368-
### 2. Scaling with Redis backplane
369-
370-
Using a Redis backplane, you achieve horizontal scaling of your SignalR application. The SignalR leverages Redis to efficiently broadcast messages across multiple servers. This allows your application to handle large user bases with minimal latency.
371-
372-
In the SignalR app, install the following NuGet package:
373-
* ` Microsoft.AspNetCore.SignalR.StackExchangeRedis`
369+
#### Add Web API to get previous operation as a backup to get lost operations
374370

375-
Below is a code snippet to configure Redis backplane in an ASP.NET Core application using the ```AddStackExchangeRedis ``` method
371+
On the client side, messages broadcast using SignalR might be received out of order or lost due to network issues. In such cases, we need a backup method to retrieve missing operations from Redis. By using the following method, we can retrieve all operations performed after the last successful client-synchronized version and return any missing operations to the requesting client.
376372

377373
```csharp
378-
builder.Services.AddSignalR().AddStackExchangeRedis("<your_Redis_connection_string>");
379-
```
380-
Configure options as needed:
381-
382-
The following example shows how to add a channel prefix in the ConfigurationOptions object.
383-
384-
```csharp
385-
builder.Services.AddDistributedMemoryCache().AddSignalR().AddStackExchangeRedis(connectionString, options =>
374+
public async Task<string> GetActionsFromServer(ActionInfo param)
386375
{
387-
options.Configuration.ChannelPrefix = "document-editor";
388-
});
389-
```
376+
try
377+
{
378+
// Initialize necessary variables from the parameters and helper class
379+
int saveThreshold = CollaborativeEditingHelper.SaveThreshold;
380+
string tableName = param.RoomName;
381+
int lastSyncedVersion = param.Version;
382+
int clientVersion = param.Version;
383+
384+
// Retrieve the database connection
385+
IDatabase database = _redisConnection.GetDatabase();
386+
387+
// Fetch actions that are effective and pending based on the last synced version
388+
List<ActionInfo> actions = await GetEffectivePendingVersion(tableName, lastSyncedVersion);
389+
390+
// Increment the version for each action sequentially
391+
actions.ForEach(action => action.Version = ++clientVersion);
392+
393+
// Filter actions to only include those that are newer than the client's last known version
394+
actions = actions.Where(action => action.Version > lastSyncedVersion).ToList();
395+
396+
// Transform actions that have not been transformed yet
397+
actions.Where(action => !action.IsTransformed).ToList()
398+
.ForEach(action => CollaborativeEditingHandler.TransformOperation(action, actions));
399+
400+
// Serialize the filtered and transformed actions to JSON and return
401+
return Newtonsoft.Json.JsonConvert.SerializeObject(actions);
402+
}
403+
catch (Exception ex)
404+
{
405+
// In case of an exception, return an empty JSON object
406+
return "{}";
407+
}
408+
}
390409

410+
```
391411

392412
Full version of the code discussed about can be found in below GitHub location.
393413

ej2-asp-core-toc.html

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -893,10 +893,10 @@
893893
<li><a href="/ej2-asp-core/document-editor/feature-module">Feature modules</a></li>
894894
<li><a href="/ej2-asp-core/document-editor/import">Import</a></li>
895895
<li><a href="/ej2-asp-core/document-editor/export">Export</a></li>
896-
<li>Collaborative Editing
896+
<li><a href="/ej2-asp-core/document-editor/collaborative-editing/overview">Collaborative Editing</a>
897897
<ul>
898-
<li><a href="/ej2-asp-core/document-editor/collaborative-editing/using-database-in-asp-net">Using Database in ASP .NET Core</a></li>
899-
<li><a href="/ej2-asp-core/document-editor/collaborative-editing/using-redis-in-asp-net">Using Redis in ASP .NET Core</a></li>
898+
<li><a href="/ej2-asp-core/document-editor/collaborative-editing/using-dot-net">Using Database in ASP .NET Core</a></li>
899+
<li><a href="/ej2-asp-core/document-editor/collaborative-editing/using-redis-cache-asp-net">Using Redis in ASP .NET Core</a></li>
900900
</ul>
901901
</li>
902902
<li><a href="/ej2-asp-core/document-editor/image">Images</a></li>

0 commit comments

Comments
 (0)