Design @mentions and #hashtags – Frontend System Design

For this exercise, let’s construct an article structured around the task of building a system to support @mentions and hashtags within a WYSIWYG rich text editor, a common feature in modern social platforms and collaborative tools.
Please do note, @mentions and rich text editor share a lot of common features, please do check out rich text editor here.
Introduction
In the dynamic landscape of web applications, the integration of @mentions and hashtags within text editors has evolved from a luxury to a near necessity. As developers, we are often tasked with creating systems that not only perform these functions but do so efficiently, accessibly, and across various devices and languages. This article will navigate through the construction of such a system, addressing the common functional and non-functional requirements, and highlighting optimizations and security measures necessary for a robust implementation.
Full Diagram can be found here.
Clarifying Questions
- How should the system differentiate and prioritize
@mentionsvs.hashtags? - What user data should be displayed in
@mentionresults? - At what user input threshold should the system begin querying for results?
- Should the list of mentions or hashtags support infinite scrolling?
- How frequently will the results be updated from the server?
- Are there any preferences on the latency and load performance?
Functional Requirements
- Support for rich text formatting, including bold, italics, and hyperlinks.
- Seamless integration of
@mentionand#hashtagfunctionality within the text editor. - Displaying a popover list for both mentions and hashtags with real-time search results.
- Navigational links in popovers that redirect to detailed user profiles or hashtag summaries.
- Real-time updates to mention and hashtag lists based on the latest server data.
Non-Functional Requirements
- Implement efficient caching strategies to minimize server hits and enhance user experience.
- Decide between Server-Side Rendering (SSR) and Client-Side Rendering (CSR) based on initial load performance and SEO considerations.
- Mobile responsiveness to ensure usability across various devices.
- Pagination support, with a discussion on the merits of offset vs cursor-based approaches.
- High performance with low latency, potentially leveraging debouncing and normalized caching.
- Internationalization support for a global user base.
- Accessibility considerations, ensuring compliance with ARIA standards and cross-browser compatibility.
- Offline mode functionality, serving cached results when no network connection is available.
- Observability measures to track and optimize system performance and user interactions.
- Appropriate HTTP protocol selection to match the real-time or batched data requirements.
Edgecases
Building a system to support @mentions and hashtags requires careful consideration of various edge cases to ensure a seamless user experience. Here are some potential edge cases and approaches for handling them:
Handling Deletions
When a user decides to remove an @mention or a #hashtag, the system should:
- Recognize the deletion in real time and remove any associated styling or interactive elements.
- If part of a
mentionorhashtagis deleted, consider the entire entity as removed to avoid partial tags. - Update the list of mentions or hashtags accordingly if they are being tracked or counted.
Handling Undos
Undo functionality is vital in text editing. For @mentions and hashtags:
- Implement a stack to keep track of user actions to allow a step-by-step undo process.
- Ensure that undoing an action restores the previous state entirely, including text and associated metadata.
Handling New Searches
When a user initiates a new search by typing @ or #:
- Immediately trigger a debounce function to avoid overloading the server with requests during rapid typing.
- Cancel any ongoing searches that are no longer relevant.
- Display a loading state to inform the user that a search is in progress, if necessary.
High-Level Architecture

The high-level architecture for a WYSIWYG rich text editor can be segmented into several key components, each responsible for distinct aspects of the editor’s functionality. The architecture diagram outlines the separation of concerns and depicts how user interactions are processed and rendered.
Server and GraphQL (GQL) Layer The server forms the backbone of the rich text editor, interacting with the database and file storage systems to save and retrieve content. GraphQL sits as an intermediary between the server and client, providing a flexible API layer that allows the client to request exactly the data it needs. This can include not just the text content but also metadata, such as user permissions, versioning information, and linked multimedia resources.
Model The Model represents the data structure and business logic of the editor. It stores the document state, including text, formatting attributes, and any embedded media. This state can be serialized for storage and transmitted to the server. The Model also exposes methods to manipulate the editor’s content programmatically, enabling operations like insertions, deletions, and formatting changes.
Controller The Controller mediates interactions between the View and the Model. It handles user input, processes commands, and mediates the rendering of the content. The Controller receives events from the View, interprets them, and makes corresponding state changes to the Model. It ensures that the user’s intentions, as expressed through interactions with the View, are accurately reflected in the editor’s data model.
Views The Views are the visual representation of the Model’s data. The Input Field View is the primary interface where users type and format their content. It listens for input events and requests the necessary updates from the Controller. The Popover View serves as an auxiliary interface for additional features like link editing or media insertion, providing a contextual UI that appears in response to specific user actions.
Interactors Interactors (Field Interactor and Popover Interactor) are the conduits through which the Views communicate with the Controller. They listen for user actions, such as keystrokes, mouse clicks, or touch events, and translate them into operations on the Model via the Controller. The Interactors are also responsible for reflecting the state of the Model back onto the Views, ensuring the UI remains in sync with the underlying data.
API Design
Our API design ensures seamless integration of @mentions and other dynamic content within a WYSIWYG rich text editor. Using GraphQL, we provide flexible and efficient querying capabilities.
GraphQL API Endpoints
- Fetching Mentions:
query getMention($MentionInput) { id, type, title, url, photo, ... // additional metadata } - Fetching Profile Data:
query getProfile($input) { name, photo } - Fetching Room Data:
query getRoom($input) { name, photo } - Creating Mentions with Content:
mutation createMessage($input) { text, metadata }
The APIs are authenticated using JWT headers, ensuring security and personalization. Whether we incorporate a WYSIWYG editor or not, our API design caters to the creation and retrieval of content-rich mentions.
Data Model
The data model for the editor is a crucial aspect that dictates how text changes are processed and stored. Here is an interface that illustrates the structure and types of the editor’s properties, ensuring a controlled and predictable state.
interface MessageInputProps {
// Interactions
onChange?: (currentTextJSON: string) => void;
onSelect?: (selectedObject: any) => void;
onBlur?: (event: Event) => void;
autoFocus: boolean;
onFetchResults: (page: number, size: number, type: string) => void;
// Styling
placeholder: string;
resultsRender: JSX.Element;
styling: StyleObject;
className: string;
// Network-related
debounceInterval: number;
showEmptyResults: boolean;
cacheTTL: number;
cacheType: 'in network' | 'apollo' | 'local' | 'session' | 'none';
networkTimeoutDuration: number; // in milliseconds
networkRetries: int;
}
Implementation Options
| Option | Pros | Cons |
|---|---|---|
| Use text area input field |
|
|
| Use contentEditable |
|
|
| External Library (Lexical/Draft.js) |
|
|
Why Option 3 is the Best Choice
Considering the needs for a robust, feature-rich, and user-friendly WYSIWYG editor, Option 3, utilizing an external library like Lexical or Draft.js, emerges as the best choice. While this option may introduce a dependency on external code and potentially increase the overall code size, the advantages it offers far outweigh these drawbacks.
Lexical and Draft.js are battle-tested libraries that provide a wide array of features out-of-the-box, including rich text capabilities and support for modern web interactions like @mentions and hashtags. Furthermore, these libraries are designed with accessibility in mind, ensuring that the editor is usable for all individuals, regardless of their abilities.
The extensive APIs offered by these libraries simplify the implementation of complex editing features, while their compatibility across different platforms and browsers ensures a consistent user experience. Although customization might be somewhat limited compared to building a solution from scratch, the trade-off is a more reliable and maintainable codebase that leverages the collective knowledge and expertise of the developer community.
Optimizations
Debouncing User Input
To enhance performance and reduce unnecessary load, user input can be debounced. This technique involves waiting for a certain amount of idle time before processing input, thereby limiting the rate at which events like keystrokes trigger updates in the editor state or re-rendering of the component.
Implementing debouncing ensures that the system is not overwhelmed by the high frequency of user actions, which is particularly beneficial when these actions lead to complex processing tasks or network requests, like fetching suggestions for @mentions or updating the live preview of the content.
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = function() {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
// Usage with a function that updates the editor state
const debouncedUpdate = debounce(updateEditorState, 250);
Caching Strategy
Caching is a crucial optimization strategy for a WYSIWYG editor. It allows us to store previously retrieved or computed data, such as user input, images, or document snapshots, so that future requests for the same data can be served faster.
The editor can implement a caching layer that stores the state of the editor or parts of it in memory. It can also persist data locally on the client’s machine using browser caching mechanisms like LocalStorage, IndexedDB, or Service Workers, which is particularly useful for offline capabilities and to quickly restore the state when the user returns to the editor.
// Example of a simple in-memory cache implementation
class EditorCache {
constructor() {
this.cache = {};
}
get(key) {
return this.cache[key];
}
set(key, value) {
this.cache[key] = value;
}
}
const cache = new EditorCache();
// Store and retrieve the editor state
cache.set('editorState', editorState);
const cachedState = cache.get('editorState');
The caching strategy also involves setting a Time To Live (TTL) for cached items and implementing an eviction policy, such as Least Recently Used (LRU), to manage memory efficiently.
Rendering @mentions
Our rich text editor implements a sophisticated text rendering method that enhances plain text with dynamic features using metadata. The renderText function works in three distinct steps:
- Read Text: The function begins by reading the provided text input, which is the base content without any formatting.
- Iterate Through Metadata: The next step is to iterate through the metadata array, applying the specified transformations to the text. For each piece of metadata, which contains offset and length, the function extracts the substring from the text and wraps it with an HTML element to apply the desired style or interaction. This could mean wrapping the text in a
<strong>tag for bold styling, a<a>tag for links, or custom elements for mentions and hashtags. - Return the Styled Characters: Finally, the function assembles the processed text fragments back into a single string, which represents the fully styled text ready to be displayed in the editor or on the webpage.
function renderText(text, metadata) {
// Initial steps...
// Styling and interaction application...
// Return processed text...
}
This method provides a seamless and interactive user experience, allowing for rich content creation within the editor.
Edge Case Management for @mentions and #hashtags
Rendering Results Popover
Ensuring the results popover for @mentions and #hashtags appears correctly involves two main positioning strategies:
- Relative to Parent: This approach uses
position: absoluteon the results, which is simple and easy to implement. However, developers must be mindful of potentialz-indexissues. - React Portals: Leveraging React Portals can help manage overflow and
z-indexissues by rendering the popover outside of the DOM hierarchy. This method requires careful manual calculations for positioning.
Network Optimization
To handle network efficiency when users search for mentions or hashtags, a combination of debouncing and caching is essential.
- Debounce Input: By implementing a debounce function, unnecessary API calls can be minimized, triggering requests only after a set idle time after the user has stopped typing.
- Caching with TTL: Utilizing caching mechanisms with Time To Live (TTL) settings helps to serve repeated requests swiftly without overloading the server.
- Normalized Data Store: A normalized data store can ensure efficient memory usage and remove data duplication by storing results based on unique identifiers.
User Interaction Handling
Addressing user interactions such as deletions, undos, and new searches is critical for a seamless user experience.
- Handling Deletions: When the user hits backspace, the editor must intelligently detect if it’s within the metadata range and update the UI accordingly.
- Handling Undos: Keeping a stack of user actions allows the editor to easily revert to previous states when the undo action is triggered.
- Handling New Searches: The editor must be able to handle new searches dynamically, showing relevant suggestions based on the latest input.
