Skip to content

AWS AppSync Subscriptions Disrupt on Network Changes

0

AppSync subscriptions stop receiving events when a user switches between network connections (e.g., from WiFi to mobile data).

To solve this error: I implemented a network status observer that monitors connection changes. The system automatically re-establishes AppSync subscriptions when a network change is detected, ensuring uninterrupted event reception.

But this causes a problem in the cost doubling. Is there a better solution to solve Subscriptions Disrupt on Network Changes problem?

1 Answer
1
Accepted Answer

Hi Fady,
Great question! This issue often comes up when managing AWS AppSync subscriptions during network transitions. Let’s break this down and find a clean, cost-effective solution.

Clarifying the Issue

You’ve implemented a network status observer to monitor connection changes and automatically re-establish subscriptions when a network switch occurs (e.g., WiFi to mobile data). However, the frequent re-subscriptions are doubling your costs, and you’re looking for a more efficient way to handle this.

Key Terms

  • AppSync Subscriptions: Real-time data delivery using GraphQL over WebSocket connections.
  • Network Disruption: Switching networks often disrupts WebSocket connections, requiring reconnection.
  • Cost Doubling: Resubscribing repeatedly can generate unnecessary costs as subscriptions are re-established.

Our Solution (the Recipe)

Here’s an optimized approach with examples to resolve the issue:

  1. Leverage AppSync’s Native Reconnection
    AWS AppSync’s WebSocket client handles automatic reconnects. Avoid manual intervention unless required. Here’s an example using the AWS Amplify SDK:

    import { API, graphqlOperation } from 'aws-amplify';
    import { onUpdateData } from './graphql/subscriptions';
    
    const subscription = API.graphql(graphqlOperation(onUpdateData))
        .subscribe({
            next: (response) => console.log('Data update:', response),
            error: (err) => console.error('Subscription error:', err),
        });

    The SDK retries connections automatically, so avoid rebuilding the subscription on every network switch.

  2. Add Connection State Listeners
    Use connection status listeners to check when the WebSocket truly disconnects:

    import { Hub } from 'aws-amplify';
    
    Hub.listen('api', (data) => {
        const { payload } = data;
        if (payload.event === 'disconnected') {
            console.log('WebSocket disconnected, monitoring...');
        }
    });

    Only re-subscribe when a confirmed disconnection occurs instead of every network status change.

  3. Throttle Manual Reconnection with Exponential Backoff
    If manual reconnections are unavoidable, implement exponential backoff to avoid flooding the system:

    let retryCount = 0;
    
    function reconnectSubscription() {
        const delay = Math.min(1000 * 2 ** retryCount, 30000); // Cap at 30 seconds
        setTimeout(() => {
            retryCount++;
            console.log(`Reconnecting... Attempt ${retryCount}`);
            // Re-initiate subscription logic here
        }, delay);
    }
  4. Optimize Subscription Filters
    Filter the subscribed data to reduce load and associated costs. For example, add filters in your GraphQL schema:

    subscription OnUpdateData($id: ID!) {
        onUpdateData(id: $id) {
            id
            value
        }
    }

    This reduces redundant data fetching and minimizes resource usage during reconnections.

  5. Validate Connection Health
    Implement a simple ping/pong mechanism to confirm the connection is inactive before resubscribing:

    const ws = new WebSocket(appSyncUrl);
    ws.onopen = () => console.log('Connection active');
    ws.onclose = () => console.log('Connection closed, reconnecting...');

Closing Thoughts

The combination of leveraging AppSync’s built-in reconnect features, connection listeners, and throttling reconnections can help you minimize unnecessary costs while ensuring seamless subscriptions. Adding GraphQL filters will further optimize performance.

I hope this clears up the issue and gives you actionable next steps! Let me know if you need more help or specific examples. 😊

Cheers, Aaron 🚀

answered a year ago
EXPERT
reviewed a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.