Session length is a core engagement metric — it tells you how long users actually spend in your product on each visit. But here's what trips people up: Amplitude calculates it automatically, yet most teams don't know how to interpret it or adjust the timeout to match their product. We'll walk through exactly how it works.
Understanding How Amplitude Measures Session Length
Amplitude automatically calculates session length by tracking when users go inactive. No custom code required — it's baked in.
Know What Amplitude Counts as a Session
A session starts with the first event and ends when the user goes inactive for 30 minutes (default). Session length is the time span from the first event to the last event in that session. When inactivity crosses the threshold, a new session begins. This is all calculated server-side by Amplitude.
import * as amplitude from '@amplitude/analytics-browser';
// Initialize with default session tracking
amplitude.init('YOUR_API_KEY', 'user_id', {
defaultTracking: {
sessions: true // Session tracking is on by default
}
});
// Sessions are now being tracked automatically
// No additional code neededView Session Length in the Dashboard
Go to Analytics and create a new Chart. In the metric dropdown, select Session Length. You'll see the average, median, or distribution of session durations for your users. Amplitude automatically segments this by user, property, or time period.
// Session length data is available via the Amplitude REST API
const response = await fetch(
'https://api.amplitude.com/2/users/export?user_id=user_123',
{
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const userData = await response.json();
const events = userData.user.events;
// Each event has session_id and session_length properties
events.forEach(event => {
console.log(`Session ID: ${event.session_id}, Length: ${event.session_length}ms`);
});
// Output: Session ID: a1b2c3d4, Length: 125000ms (2 min 5 sec)Customize Session Timeout for Your Product
The 30-minute default works for many products, but not all. You can change the session timeout when you initialize the SDK.
Set a Custom Session Timeout
Pass sessionTimeoutMillis to your init config. This sets how many milliseconds of inactivity end the current session. Use 15 minutes for fast-paced apps (mobile, real-time collab), 60 minutes for tools where users tab-switch frequently, or 5 minutes for high-engagement flows.
import * as amplitude from '@amplitude/analytics-browser';
// Set session timeout to 15 minutes (900,000 milliseconds)
amplitude.init('YOUR_API_KEY', 'user_id', {
sessionTimeoutMillis: 900000,
defaultTracking: {
sessions: true
}
});
// Now sessions end after 15 minutes of inactivity
// Events after that gap start a new sessionVerify the Timeout is Working
Log in as a test user and trigger an event. Note the session_id. Wait for slightly longer than your timeout period, then trigger another event. Check the User Activity or Events tab in Amplitude — you'll see a different session_id on the second event. This confirms the timeout fired and started a new session.
// Test your session configuration
amplitude.track('user_login');
console.log('Event 1 tracked with session timeout active');
// Wait 16 minutes (longer than 15-minute timeout)...
// Then trigger another event
amplitude.track('user_action');
// This event will have a different session_id than event 1
// Session length of the first session = ~16 minutes
// Session length of the second session = ~0 (just started)Export and Analyze Session Data
Once you've got sessions configured, export the raw data for custom analysis or deeper segmentation.
Pull Session Data via the Export API
Use the Users Export endpoint to download event-level data, including session_id and session_length for every event. This gives you the raw material to calculate custom metrics: average session length per user, engagement tiers, session length vs. conversion, etc.
// Export events with session data for a single user
async function getSessionData(userId, secretKey) {
const response = await fetch(
`https://api.amplitude.com/2/users/export?user_id=${userId}`,
{
method: 'GET',
headers: {
'Authorization': `Bearer ${secretKey}`
}
}
);
const data = await response.json();
return data.user.events.map(event => ({
session_id: event.session_id,
session_length_ms: event.session_length,
event_time: event.event_time,
event_type: event.event_type
}));
}
const sessions = await getSessionData('user_123', 'YOUR_SECRET_KEY');
sessions.forEach(s => {
console.log(`${s.event_type}: ${s.session_length_ms / 1000}s`);
});
// Output: page_view: 45s, button_click: 120s, etc.Calculate Aggregate Session Metrics
Once you have the raw events, group by session and calculate what you need: average duration, sessions under 1 minute, longest sessions, session length by user type, etc. This is easier than relying on the dashboard alone.
// Calculate session length statistics
function analyzeSessionMetrics(events) {
const sessionMap = new Map();
// Group events by session_id and find max session_length per session
events.forEach(event => {
const sid = event.session_id;
const len = event.session_length;
if (!sessionMap.has(sid) || sessionMap.get(sid) < len) {
sessionMap.set(sid, len);
}
});
const sessionLengths = Array.from(sessionMap.values());
const avgMs = sessionLengths.reduce((a, b) => a + b, 0) / sessionLengths.length;
const avgSeconds = Math.round(avgMs / 1000);
const shortSessions = sessionLengths.filter(len => len < 60000).length;
return {
total_sessions: sessionLengths.length,
avg_length_seconds: avgSeconds,
sessions_under_1min: shortSessions,
pct_short_sessions: ((shortSessions / sessionLengths.length) * 100).toFixed(1) + '%'
};
}
const metrics = analyzeSessionMetrics(events);
console.log(JSON.stringify(metrics, null, 2));
// Output: {"total_sessions": 42, "avg_length_seconds": 180, "sessions_under_1min": 8, "pct_short_sessions": "19.0%"}Common Pitfalls
- Confusing session_length with session duration. Session_length is time from first event to last event. It doesn't include idle time. If a user opens your app, clicks once, then leaves for 30 minutes, that session_length is ~0ms.
- Not testing your session timeout. If you change from 30 to 60 minutes mid-month, your data gets fragmented — earlier sessions are shorter, later ones are longer. Always test in a staging environment first and plan rollouts.
- Forgetting that session length metrics in the dashboard are aggregates. A median of 2 minutes doesn't tell you how many users have zero-second sessions. Dig into the distribution or export raw data for clarity.
- Using session_length for user intent analysis without context. A 30-second session could mean engaged power user (quick task) or confused new user (gave up). Always cross-reference with event types and conversion data.
Wrapping Up
Session length in Amplitude is calculated automatically as the time span from first to last event, with sessions breaking on 30 minutes of inactivity (configurable). Set the timeout to match your product behavior, monitor it in the dashboard, and export raw data when you need to dig deeper into engagement patterns. If you want session metrics tracked consistently across multiple analytics tools and analyzed in one place, Product Analyst can help.