Skip to main content

SignalR Setup Complete ✅

Baseline SignalR implementation with Redis backplane is now complete!

What Was Done

1. ✅ Packages Installed

  • Microsoft.AspNetCore.SignalR (v9.0.0)
  • Microsoft.AspNetCore.SignalR.StackExchangeRedis (v9.0.0)
  • StackExchange.Redis (v2.8.16)

2. ✅ Hubs Created

  • SocialHub.cs - Real-time social feed updates (posts, likes, comments)
  • NotificationHub.cs - User notifications
  • AdminHub.cs - Admin moderation queue updates

3. ✅ Configuration Added

  • SignalR configured in Program.cs with Redis backplane support
  • JWT Bearer authentication configured for SignalR WebSocket connections
  • Redis connection configuration added to appsettings.json
  • Hubs mapped: /hubs/social, /hubs/notifications, /hubs/admin

4. ✅ Controller Updates

  • SocialController updated to send real-time updates:
    • CreatePost - Broadcasts new posts
    • LikePost - Sends like updates
    • UnlikePost - Sends unlike updates
    • AddComment - Sends comment updates

Next Steps

1. Configure Redis Connection

For Local Development:

// appsettings.Development.json
{
"Redis": {
"ConnectionString": "localhost:6379",
"Enabled": true
}
}

For Staging/Production (AWS ElastiCache):

// appsettings.Production.json or Environment Variable
{
"Redis": {
"ConnectionString": "reelog-valkey-staging.oe3wvy.cache.amazonaws.com:6379",
"Enabled": true
}
}

Environment Variable (Recommended for ECS):

Redis__ConnectionString=reelog-valkey-staging.oe3wvy.cache.amazonaws.com:6379
Redis__Enabled=true

2. Enable Redis in Configuration

Update appsettings.json or set environment variable:

{
"Redis": {
"ConnectionString": "your-redis-connection-string",
"Enabled": true // Change to true to enable Redis backplane
}
}

Note: If Enabled: false, SignalR will work in single-server mode (fine for development).

3. Test SignalR Connection

Create a simple HTML test file:

<!DOCTYPE html>
<html>
<head>
<title>SignalR Test</title>
<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@latest/dist/browser/signalr.min.js"></script>
</head>
<body>
<h1>SignalR Test</h1>
<div id="messages"></div>
<button onclick="connect()">Connect</button>
<button onclick="disconnect()">Disconnect</button>

<script>
let connection = null;

function connect() {
const token = prompt("Enter your JWT token:");

connection = new signalR.HubConnectionBuilder()
.withUrl("https://your-api-url/hubs/social", {
accessTokenFactory: () => token
})
.withAutomaticReconnect()
.build();

connection.on("NewPost", (post) => {
document.getElementById("messages").innerHTML +=
`<p>New post: ${post.content}</p>`;
});

connection.on("PostLiked", (data) => {
document.getElementById("messages").innerHTML +=
`<p>Post ${data.postId} liked! Count: ${data.likeCount}</p>`;
});

connection.on("CommentAdded", (data) => {
document.getElementById("messages").innerHTML +=
`<p>Comment added to post ${data.postId}</p>`;
});

connection.start()
.then(() => {
console.log("Connected!");
document.getElementById("messages").innerHTML += "<p>✅ Connected to SignalR</p>";
})
.catch(err => {
console.error("Connection error:", err);
document.getElementById("messages").innerHTML += `<p>❌ Error: ${err}</p>`;
});
}

function disconnect() {
if (connection) {
connection.stop();
document.getElementById("messages").innerHTML += "<p>Disconnected</p>";
}
}
</script>
</body>
</html>

4. Test Real-Time Updates

  1. Start your API (with Redis enabled if you have it)
  2. Open test HTML file in browser
  3. Connect with a valid JWT token
  4. Create a post via API (POST /api/social/posts)
  5. See the update appear instantly in the browser!

5. ALB Configuration (For Production)

When deploying to AWS ECS with ALB, ensure:

  1. Sticky Sessions Enabled (for multi-server scaling):

    • ALB Target Group → Attributes
    • Enable stickiness: lb_cookie
    • Duration: 3600 seconds
  2. WebSocket Support:

    • ALB automatically supports WebSockets
    • No additional configuration needed
  3. Health Checks:

    • Ensure health check endpoint (/health) works
    • SignalR connections don't interfere with health checks

How It Works

Single Server Mode (Redis Disabled)

Client → SignalR Hub → All Connected Clients
  • Works fine for development
  • Limited to single server

Multi-Server Mode (Redis Enabled)

Client → Server 1 → Redis → Server 2 → Client
  • Scales horizontally across multiple ECS instances
  • All servers share connection state via Redis

Real-Time Events

SocialHub Events

Client Receives:

  • NewPost - When a new post is created
  • PostLiked - When a post is liked
  • PostUnliked - When a post is unliked
  • CommentAdded - When a comment is added

Client Can Call:

  • SubscribeToUser(userId) - Subscribe to user's posts
  • SubscribeToCircle(circleId) - Subscribe to circle updates
  • SubscribeToPost(postId) - Subscribe to post updates

NotificationHub Events

Client Receives:

  • NotificationReceived - When user receives a notification

AdminHub Events

Client Receives:

  • NewModerationItem - When new content needs moderation
  • NewReport - When a new report is created

Frontend Integration (Next Steps)

When building frontend apps, use:

Web App (React/Next.js):

npm install @microsoft/signalr

Mobile App (React Native):

npm install @microsoft/signalr
npm install react-native-get-random-values

See docs/infrastructure/real-time-updates-strategy.md for complete frontend integration guide.

Troubleshooting

Redis Connection Issues

Error: Unable to connect to Redis

Solutions:

  1. Check Redis connection string is correct
  2. Ensure Redis is running (local) or accessible (AWS)
  3. Check security groups (AWS ElastiCache)
  4. Set Redis:Enabled: false to disable Redis temporarily

SignalR Connection Issues

Error: 401 Unauthorized

Solutions:

  1. Ensure JWT token is valid
  2. Check token is passed correctly (query string for WebSocket)
  3. Verify JWT Bearer configuration in Program.cs

No Real-Time Updates

Check:

  1. SignalR connection is established (check browser console)
  2. Client is subscribed to correct groups
  3. Server is sending updates (check logs)
  4. Redis is working (if multi-server)

Files Modified

  • FishingLog.API.csproj - Added SignalR packages
  • Program.cs - Configured SignalR with Redis
  • appsettings.json - Added Redis config
  • appsettings.Development.json - Added Redis config
  • SocialController.cs - Added real-time updates
  • Hubs/SocialHub.cs - Created
  • Hubs/NotificationHub.cs - Created
  • Hubs/AdminHub.cs - Created

Summary

SignalR baseline is complete!

What works now:

  • Real-time post creation updates
  • Real-time like/unlike updates
  • Real-time comment updates
  • Redis backplane support (when enabled)
  • JWT authentication for SignalR

Next steps:

  1. Configure Redis connection string
  2. Enable Redis (Enabled: true)
  3. Test with HTML test file
  4. Integrate with frontend apps when ready

Status: ✅ Baseline Complete - Ready for Testing
Last Updated: December 2025