Presence Indicator Implementation (Who Is Online Now) on Website
A green dot next to an avatar—simple to look at, but behind it stands a concrete infrastructure challenge: the server must know who is connected right now and notify other users when this state changes. Applications: support chat, user profiles, course participant lists, collaborative editing.
How "Online" Is Determined
Three approaches with different accuracy levels:
Heartbeat via WebSocket/SSE—most precise. While the connection is active, the user is online. On disconnect—disconnect event. Offline detection delay: seconds.
Heartbeat via HTTP—client sends POST /api/presence/ping every 30 seconds. If no ping for longer than 60 seconds—user is considered offline. Detection delay: up to 60 seconds. Simpler to implement, doesn't require persistent connection.
Last seen—soft variant. Not "online/offline," but "was 3 minutes ago." Updates on any API request. Useful for privacy (user chooses whether to show exact status).
For most websites, HTTP heartbeat is sufficient—no need to maintain WebSocket connection just for a single dot.
Redis Presence Storage
Presence is stored in Redis, not PostgreSQL. Reason: frequent writes (every 30 seconds per user), TTL logic, no persistence needed.
class PresenceService
{
private const TTL = 90; // seconds without ping = offline
public function markOnline(int $userId, string $context = 'global'): void
{
Redis::setex("presence:{$context}:{$userId}", self::TTL, now()->timestamp);
// Notify channel if this is first appearance
$wasOnline = Redis::exists("presence_flag:{$context}:{$userId}");
if (!$wasOnline) {
Redis::setex("presence_flag:{$context}:{$userId}", self::TTL + 10, 1);
broadcast(new UserCameOnline($userId, $context));
}
}
public function markOffline(int $userId, string $context = 'global'): void
{
Redis::del("presence:{$context}:{$userId}");
Redis::del("presence_flag:{$context}:{$userId}");
broadcast(new UserWentOffline($userId, $context));
}
public function getOnlineUsers(string $context = 'global'): array
{
$keys = Redis::keys("presence:{$context}:*");
return array_map(fn($k) => (int) last(explode(':', $k)), $keys);
}
public function isOnline(int $userId, string $context = 'global'): bool
{
return (bool) Redis::exists("presence:{$context}:{$userId}");
}
}
The $context parameter allows splitting presence by sections: chat_room:42, course:17, global.
Heartbeat Endpoint
Route::middleware('auth:sanctum')->post('/api/presence/ping', function (Request $request) {
app(PresenceService::class)->markOnline(
$request->user()->id,
$request->input('context', 'global')
);
return response()->json(['ok' => true]);
});
The client calls this endpoint on page load and then every 30 seconds:
const ping = () => fetch('/api/presence/ping', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken },
body: JSON.stringify({ context: 'global' }),
});
ping();
const interval = setInterval(ping, 30_000);
// Cleanup when closing tab
window.addEventListener('beforeunload', () => {
clearInterval(interval);
navigator.sendBeacon('/api/presence/offline'); // fire-and-forget
});
navigator.sendBeacon—the only reliable way to send a request when closing a tab. Regular fetch in beforeunload may be interrupted by the browser.
Broadcast Events
class UserCameOnline implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(
public readonly int $userId,
public readonly string $context,
) {}
public function broadcastOn(): Channel
{
return new Channel("presence.{$this->context}");
}
}
Indicator in Interface
// Initial state is loaded with the page
const onlineUsers = new Set(initialOnlineUserIds);
function updateDot(userId, isOnline) {
const dot = document.querySelector(`[data-user-id="${userId}"] .presence-dot`);
if (!dot) return;
dot.classList.toggle('bg-green-500', isOnline);
dot.classList.toggle('bg-gray-300', !isOnline);
dot.title = isOnline ? 'Online' : 'Offline';
}
Echo.channel('presence.global')
.listen('UserCameOnline', ({ userId }) => {
onlineUsers.add(userId);
updateDot(userId, true);
})
.listen('UserWentOffline', ({ userId }) => {
onlineUsers.delete(userId);
updateDot(userId, false);
});
Presence via Laravel Presence Channels
If using Laravel Echo + Pusher/Reverb, you can use the built-in Presence Channels mechanism—it automatically manages the list of connected users:
Echo.join('room.42')
.here((users) => { /* initial list */ })
.joining((user) => updateDot(user.id, true))
.leaving((user) => updateDot(user.id, false));
The backend simply authorizes the channel and returns user data:
Broadcast::channel('room.{roomId}', function (User $user, int $roomId) {
if ($user->canAccessRoom($roomId)) {
return ['id' => $user->id, 'name' => $user->name, 'avatar' => $user->avatar_url];
}
});
Timeline
- Heartbeat ping + Redis TTL + indicator: 1–2 days
- Broadcast on status change (UserCameOnline / Offline): 1 day
- Presence Channels via Laravel Echo: 1 day
- Last seen instead of online/offline: 0.5 day
- Privacy settings (hide status): +0.5 day







