Skip to content

Feedback: speech-to-text-universal-streaming-common-session-errors-and-closures

Original URL: https://www.assemblyai.com/docs/speech-to-text/universal-streaming/common-session-errors-and-closures
Category: speech-to-text
Generated: 05/08/2025, 4:23:32 pm


Generated: 05/08/2025, 4:23:31 pm

Technical Documentation Analysis & Recommendations

Section titled “Technical Documentation Analysis & Recommendations”

The documentation covers an important topic but suffers from structural issues, missing implementation guidance, and unclear explanations that could frustrate users during error handling scenarios.

Issues:

  • Redundant heading structure (identical main and subheading)
  • Poor information hierarchy
  • Missing quick reference section

Recommendations:

# Common Session Errors and Closures
## Overview
Brief explanation of WebSocket closures vs errors...
## Quick Reference
[Add error code summary table]
## Understanding Closures vs Errors
[Current explanation, but clearer]
## Error Codes and Descriptions
[Current table with improvements]
## Implementation Guide
[New section - see below]
## Troubleshooting
[New section - see below]

Add Implementation Examples:

## Implementation Guide
### Basic Error Handling Pattern
```python
def on_close(ws, close_status_code, close_msg):
if close_status_code == 3005:
if "Session Expired" in close_msg:
# Restart session logic
restart_session()
elif "Input duration violation" in close_msg:
# Adjust audio chunk size
adjust_chunk_size()
elif close_status_code == 1008:
# Handle authentication issues
handle_auth_error(close_msg)
def on_error(ws, error):
logger.error(f"WebSocket error: {error}")
# Error cleanup logic here

Add Missing Error Details:

  • Network timeout scenarios
  • Retry strategies and backoff patterns
  • Rate limiting specifics
  • Audio format validation errors

Current table lacks:

  • Severity levels
  • Recommended actions
  • Retry guidelines

Enhanced table structure:

CodeReasonSeverityRecommended ActionRetry Safe?
3005Session ExpiredNormalStart new sessionYes
3005Input duration violationErrorFix audio chunks, retryYes
1008Too many concurrent sessionsWarningWait and retryYes (with backoff)

Fix these ambiguities:

<!-- Instead of: "Audio sent faster than real-time" -->
Audio Transmission Rate Exceeded: You're sending audio data faster than it can be processed.
For example, sending 2 seconds of audio in 1 second of real time.
**Solution:** Implement proper timing to send audio chunks at or slightly below real-time speed.
<!-- Instead of: "Message is not valid (i.e. '[]')" -->
Invalid Message: The message structure is incorrect or empty.
**Common causes:**
- Empty arrays: `[]`
- Missing required fields in JSON messages
- Malformed message objects
**Solution:** Validate message structure before sending.
## Troubleshooting Guide
### Session Keeps Closing with Code 3005
1. **Check audio chunk timing**: Ensure chunks are 50-1000ms
2. **Verify message format**: Validate JSON structure
3. **Monitor session duration**: Sessions have 3-hour limit
### Authentication Errors (Code 1008)
1. **Verify API key**: Check [API Keys page](link)
2. **Check account status**: Ensure sufficient balance
3. **Monitor concurrency**: Review [Rate Limits](link)
### Frequent Disconnections
- Check network stability
- Implement reconnection logic with exponential backoff
- Monitor audio quality and format compliance

6. Add Code Examples for Different Languages

Section titled “6. Add Code Examples for Different Languages”
## Language-Specific Examples
### JavaScript
```javascript
websocket.onclose = function(event) {
console.log(`Connection closed: ${event.code} - ${event.reason}`);
if (event.code === 3005 && event.reason.includes("Session Expired")) {
reconnectSession();
}
};

[Add Python example]

[Add debugging commands]

### 7. **Improve User Experience**
**Add these UX improvements:**
- **Visual indicators**: Use icons or colors for error severity
- **Cross-references**: Link to related documentation sections
- **Search optimization**: Add common search terms users might use
- **Progressive disclosure**: Hide advanced details behind expandable sections
### 8. **Missing Proactive Guidance**
**Add prevention strategies:**
```markdown
## Best Practices to Prevent Errors
### Audio Handling
- Validate audio format before streaming
- Implement proper chunk sizing (100-500ms recommended)
- Add audio quality checks
### Connection Management
- Implement heartbeat/ping mechanisms
- Use connection pooling for high-volume applications
- Monitor and log connection metrics
### Error Recovery
- Implement exponential backoff for retries
- Cache audio data for replay after reconnection
- Set up monitoring and alerting for error patterns

The current note is helpful but could be more actionable:

<Note title="Implementation Example: Handling Session Expiration">
```python
def handle_session_closure(status_code, reason):
if status_code == 3005 and "Session Expired" in reason:
logger.info("Session expired, creating new session...")
# Save current state
current_audio_position = save_current_state()
# Create new session
new_session = create_new_streaming_session()
# Resume from where we left off
resume_streaming_from(current_audio_position)
return new_session
# Handle other closure reasons...

Note that on_error is NOT called for planned closures like session expiration.

## Summary of Actionable Items
1. **Immediate fixes**: Restructure headings, enhance table with actionable columns
2. **Short-term additions**: Add code examples, troubleshooting section, prevention strategies
3. **Long-term improvements**: Multi-language examples, interactive debugging tools, comprehensive error recovery patterns
These changes will transform the documentation from a simple reference into a practical guide that helps users both understand and effectively handle streaming session issues.
---