Designing a Scalable User Account System with Dynamic Feeds and Favorites
This article presents a practical architecture for user registration, authentication, dynamic content feeds, and favorites. It covers password security, session management, feed fan-out strategies, event-driven publishing, idempotent favorite operations, cursor-based pagination, caching, database indexing, sharding considerations, and data protection.
1. Background and Core Challenges
On any platform built around content consumption and social interaction, the user account system is the foundation for nearly every business capability. From a user’s first visit, registration, login, session management, content publishing, and favorites all depend on reliable backend services.
These features introduce several engineering challenges:
- How can account security be maintained?
- How can login traffic be handled under high concurrency?
- How should dynamic content and favorites be modeled to support both real-time access and future growth?
- How can the system avoid data leaks and service interruptions?
Poor implementation may result in anything from a degraded user experience to serious security incidents or service unavailability.
This article examines registration and authentication as well as dynamic feeds and favorites from a general engineering perspective. It focuses on design principles and implementation strategies that can be applied across different products.
2. Registration and Login: Building the First Security Barrier
2.1 Registration Flow
A standard registration process typically includes the following steps:
- The user submits basic information, such as a username, phone number or email address, and password.
- The system checks uniqueness to prevent duplicate accounts.
- The system sends a verification code or link to confirm control of the contact method.
- The backend hashes the password and writes the user record.
- After successful registration, the system signs the user in automatically and creates default user settings.
A key concern is protecting the verification-code delivery endpoint from abuse. Without appropriate controls, automated programs can consume large amounts of SMS or email capacity. Common countermeasures include:
- Rate limiting by IP address or device
- Requiring a CAPTCHA before sending a code
- Dynamically increasing the interval between delivery attempts
- Limiting code validity periods and verification failures
Pseudocode: Registration Request Processing1. Validate that all required parameters are present2. Check whether the username or phone number already exists(use a unique index to guarantee concurrency safety)3. Generate and send a verification code(rate limit: one request per phone number every 60 seconds)4. Validate the code submitted by the user5. Hash the password with a unique salt6. Insert the user record and create the user settings record7. Return the authenticated session
2.2 Secure Password Storage
Password storage is a central part of the security architecture. The established practice is to use a one-way hash with a randomly generated salt to defend against rainbow-table attacks. The selected algorithm should support an adaptive computational cost, and password verification should recalculate the hash for each login attempt.
Important principles include:
- Generate a separate, cryptographically random salt for every user.
- Store the salt, algorithm parameters, and hash output together so the algorithm can be upgraded later.
- Never store plaintext passwords or passwords encrypted with a reversible algorithm.
- Protect all password-related requests with encrypted transport to prevent interception by man-in-the-middle attackers.
2.3 Session and Authentication Management
After a successful login, the system issues a session credential to the client. Two common approaches are server-side sessions and stateless tokens such as JWTs.
| Approach | Advantages | Disadvantages |
|---|---|---|
| Session | Can be actively revoked and centrally managed | Requires server-side storage; distributed deployments need session synchronization |
| Token | Stateless, easy to scale horizontally, and suitable for mobile clients | More difficult to revoke; requires an additional blacklist or revocation mechanism |
In production systems, a hybrid approach is often used: a short-lived access token paired with a long-lived refresh token, while the server maintains revocable session records.
Regardless of the selected approach, the design should account for single sign-on, multi-device login, and alerts for logins from unusual locations. Device fingerprints and risk-control checks may be introduced when necessary.
3. Dynamic Content: From Data Modeling to Feed Delivery
3.1 Core Data Model
A dynamic post generally refers to short-form user-generated content. It may contain text, image references, or video references. A simplified data model includes:
- Dynamic post ID as the primary key, potentially generated with the Snowflake algorithm for distributed uniqueness
- Author ID
- Content body, such as text or media references
- Visibility scope, including public, followers-only, or private
- Creation and update timestamps
- Deletion marker for logical deletion, recovery, and auditing
List views also require related aggregate fields, such as like, comment, and favorite counts. These counts should not be recalculated in real time for every query. Instead, they should be maintained through asynchronous jobs or idempotent update mechanisms. Repeated aggregation at read time can place significant pressure on the database.
3.2 Two Main Feed Delivery Models
Dynamic content is commonly accessed through two paths:
- A personal profile feed, queried by author ID with pagination
- A following or recommendation feed, which aggregates content from multiple users and sorts it by time or personalized ranking
For a personal profile, a composite index on author ID and creation time provides efficient retrieval.
For a following feed, the industry commonly uses two approaches:
- Push model, or write fan-out: When a user publishes a post, the system writes the post ID to the inbox list of every follower. This provides fast reads but creates substantial write amplification and is not suitable for accounts with very large audiences.
- Pull model, or read fan-out: When the feed is requested, the system retrieves recent posts from all followed users and merges and sorts them. This reduces write pressure but increases read amplification and depends heavily on high-performance caching.
Large-scale systems often combine both approaches. Ordinary users can use the push model, while accounts with extremely large audiences use the pull model. Local caching and merge queries can then balance read and write pressure.
3.3 Consistency During Publishing
Publishing a dynamic post is not limited to inserting a database record. It may also involve media uploads, content moderation, follower notifications, indexing, and cache updates.
To reduce coupling, an asynchronous, event-driven architecture can be used:
Flow:1. The client submits the dynamic content request2. The server persists the post with a "pending review" status3. The server publishes a moderation event to a message queue4. After approval, the post status is changed to "published"5. Follow-up tasks update notifications, indexes, and caches
This approach allows the user to receive a quick submission-success response while moving time-consuming work out of the request path.
4. Favorites: Reliability and Data Consistency
4.1 Favorite Data Model
A favorite is fundamentally a many-to-many relationship between a user and a piece of content. The core tables commonly include:
- A favorite records table containing the user ID, content ID, creation time, and source device
- A composite unique constraint on
(user_id, content_id)to prevent duplicate favorites - An optional favorite-folder or grouping table for user-defined categories
Favorite operations must be idempotent. If a user repeatedly clicks “Favorite” or “Unfavorite,” the system should correctly handle the state transition without creating inconsistent records.
The operation should be based on whether the current relationship exists in the data store rather than relying solely on the order of client requests.
4.2 Pagination and Performance Optimization
Favorite lists may contain a large amount of historical data and generally need reverse chronological pagination. Using OFFSET becomes inefficient on deep pages because the database must scan and skip an increasing number of rows.
Cursor-based pagination is preferable. The cursor can be based on the favorite timestamp or record ID and passed to the next request.
-- First pageSELECT * FROM favoritesWHERE user_id = ?ORDER BY created_at DESC, id DESCLIMIT 20;-- Next page, using the cursor from the last item on the previous pageSELECT * FROM favoritesWHERE user_id = ?AND (created_at < ? OR (created_at = ? AND id < ?))ORDER BY created_at DESC, id DESCLIMIT 20;
This method allows the database to use indexes consistently and avoids scanning large offsets.
For favorite counts associated with popular content, a counter table combined with asynchronous incremental updates can reduce contention. This avoids triggering a direct counter update on every favorite operation.
4.3 Caching and Consistency
Favorite status is frequently queried. For example, a content detail page may need to display whether the current user has favorited a post.
This relationship is a typical hot data item suitable for caching. A common approach is to construct a cache key from the user ID and content ID. If the key is found, the cached result is returned directly. On a cache miss, the system queries the database and writes the result back to the cache.
Cache updates should occur only after the favorite operation succeeds. The system can then use explicit deletion or asynchronous refresh to provide eventual consistency.
Cache invalidation must also address cache penetration. For nonexistent favorite relationships, a short-lived empty-value cache can prevent repeated malicious or accidental requests from reaching the database.
5. Data-Layer Design Considerations
5.1 Indexing Strategy
Recommended indexes include:
- User table: A unique index on phone number or email, plus a non-unique index on nickname
- Dynamic post table: A composite index on
(user_id, created_at)and an index on(status, created_at)for moderation-flow queries - Favorites table: A unique index on
(user_id, content_id)and a composite index on(user_id, created_at)for list queries
5.2 When to Introduce Sharding
As user and content volumes grow, a single table may become a bottleneck. The sharding key should be considered during the planning stage:
- User data can be partitioned by user ID.
- Dynamic posts can be partitioned by author ID.
- Favorite records can be partitioned by user ID.
After sharding, cross-user following-feed queries become more complex. An aggregation layer or cache layer is typically needed to address this complexity.
Not every system needs database sharding from the beginning. However, the architecture should leave room for future expansion. A proxy layer or encapsulated data-access layer can reduce the amount of application code that must change later.
5.3 Complementary Roles of Databases and Caches
For high-frequency reads, in-memory caches should be used where appropriate to reduce database load.
For write-heavy operations, message queues can absorb traffic spikes and combine short-lived updates into batch writes. For example, like-count events can be placed into a queue and processed by consumers that update the database in batches, reducing row-lock contention.
6. Security and Compliance
User systems contain substantial amounts of private data and must follow applicable data-protection requirements. Important measures include:
- Encrypt all data in transit.
- Mask or encrypt sensitive fields such as phone numbers and email addresses in the database, decrypting them only when necessary.
- Never record plaintext passwords, tokens, or other sensitive credentials in logs.
- Apply the principle of least privilege to administrative operations and retain audit logs.
- After account deletion, delete or anonymize personal data according to applicable compliance requirements.
Login endpoints must also resist brute-force attacks. The overall security design should include measures such as:
- Locking accounts after repeated failures
- Requiring an additional CAPTCHA or verification step
- Rate limiting by IP address
- Detecting abnormal behavior through risk-control mechanisms
7. Conclusion
User accounts, dynamic feeds, and favorites may appear to be basic platform features, but they involve high-concurrency processing, data consistency, security protection, and long-term scalability.
A reliable implementation requires deliberate architectural planning at every stage:
- Rate limiting and validation at the registration entry point
- A hybrid push-and-pull strategy for dynamic feeds
- Idempotent operations and caching for favorites
- Appropriate indexes, asynchronous processing, and extensible data-access abstractions
Together, these practices help create a secure, efficient, and evolvable foundation for user interaction systems.
