Home | History | Annotate | Download | only in gcm
      1 page.title=Implementing GCM Server
      2 @jd:body
      3 
      4 <div id="qv-wrapper">
      5 <div id="qv">
      6 
      7 <h2>In this document</h2>
      8 
      9 <ol class="toc">
     10   <li><a href="#role">Role of the 3rd-party Application Server</a></li>
     11   <li><a href="#choose">Choosing a GCM Connection Server</a></li>
     12   <li><a href="#send-msg">Sending Messages</a>
     13     <ol class="toc">
     14 
     15       <li><a href="#target">Target</a></li>
     16       <li><a href="#payload">Payload</a></li>
     17       <li><a href="#params">Message parameters</a>
     18     </ol>
     19     </li>
     20   <li><a href="#adv">Messaging Concepts and Best Practices</a>
     21 
     22    <ol class="toc">
     23 
     24       <li><a href="#collapsible">Send-to-Sync vs. Messages with Payload</a></li>
     25       <li><a href="#ttl">Setting an Expiration Date for a Message</a></li>
     26       <li><a href="#multi-senders">Receiving Messages from Multiple Senders</a>
     27       <li><a href="#lifetime">Lifetime of a Message</a>
     28       <li><a href="#throttling">Throttling</a>
     29     </ol>
     30 
     31 </li>
     32   </li>
     33 
     34 </ol>
     35 
     36 <h2>See Also</h2>
     37 
     38 <ol class="toc">
     39 <li><a href="server-ref.html">Server Reference</a></li>
     40 <li><a href="gs.html">Getting Started</a></li>
     41 <li><a href="client.html">Implementing GCM Client</a></li>
     42 <li><a href="ccs.html">Cloud Connection Server (XMPP)</a></li>
     43 <li><a href="http.html">HTTP Connection Server</a></li>
     44 
     45 
     46 </ol>
     47 
     48 </div>
     49 </div>
     50 
     51 
     52 <p>The server side of Google Cloud Messaging (GCM) consists of two components:</p>
     53 <ul>
     54 <li>Google-provided <strong>GCM Connection Servers</strong>
     55 take messages from a <a href="{@docRoot}google/gcm/server.html#role">3rd-party app server</a>
     56 and send them to a GCM-enabled
     57 application (the &quot;client app&quot;) running on a device. For example,
     58 Google provides connection servers for <a href="{@docRoot}google/gcm/http.html">
     59 HTTP</a> and <a href="{@docRoot}google/gcm/ccs.html">XMPP (CCS)</a> (XMPP).</li>
     60 <li>A <strong>3rd-party application server</strong> that you must implement. This application
     61 server sends data to a GCM-enabled client app via the chosen GCM connection server.</li>
     62 </ul>
     63 </p>
     64 
     65 <p>A full GCM implementation requires both a client implementation and a server
     66 implementation. For more
     67 information about implementing the client side, see <a href="client.html">
     68 Implementing GCM Client</a>.</p>
     69 
     70 
     71 <h2 id="role">Role of the 3rd-party Application Server</h2>
     72 
     73 <p>Before you can write client apps that use the GCM feature, you must
     74 have an  application server that meets the following criteria:</p>
     75 
     76 <ul>
     77   <li>Able to communicate with your client.</li>
     78   <li>Able to  fire off properly formatted requests to the GCM server.</li>
     79   <li>Able to handle requests and resend them as needed, using
     80 <a href="http://en.wikipedia.org/wiki/Exponential_backoff">exponential back-off.</a></li>
     81   <li>Able to store the API key and client registration IDs. In HTTP, the API key is
     82 included in the header of POST requests that send messages. In XMPP, the API key is
     83 used in the SASL PLAIN authentication request as a password to authenticate the connection.</li>
     84  <li>Able to generate message IDs to uniquely identify each message it sends. Message IDs
     85 should be unique per sender ID.</li>
     86 </ul>
     87 
     88 <p>Here are the basic steps you follow to implement your 3rd-party app server:</p>
     89 
     90 <ul>
     91       <li>Decide which GCM connection server(s) you want to use. Note that if you want to use
     92       upstream messaging from your client applications, you must use XMPP (CCS). For a more detailed
     93       discussion of this, see <a href="#choose">
     94       Choosing a GCM Connection Server</a>.</li>
     95       <li>Decide how you want to implement your app server. We provide helper libraries and code
     96 samples to assist you with your 3rd-party app server implementation. For example:
     97         <ul>
     98           <li>If you decide to use the HTTP connection server, you can use the
     99 GCM server helper library and demo app to help in implementing your app server.</li>
    100           <li>If you decide to use the XMPP connection server, you can use
    101 the provided Python or Java <a href="http://www.igniterealtime.org/projects/smack/">
    102 Smack</a> demo apps as a starting point.</li>
    103         <li>Note that Google AppEngine does not support connections to XMPP (CCS).</li>
    104         </ul>
    105       </li>
    106     </ul>
    107   </li>
    108 </ul>
    109 
    110 
    111 <h2 id="choose">Choosing a GCM Connection Server</h2>
    112 
    113 <p>Currently GCM provides two connection servers: <a href="{@docRoot}google/gcm/http.html">
    114 HTTP</a> and <a href="{@docRoot}google/gcm/ccs.html">XMPP (CCS)</a>. You can use them
    115 separately or in tandem. XMPP (CCS) messaging differs from HTTP messaging in the following ways:</p>
    116 <ul>
    117   <li>Upstream/Downstream messages
    118     <ul>
    119       <li>HTTP: Downstream only, cloud-to-device up to 4KB of data. </li>
    120       <li>XMPP (CCS): Upstream and downstream (device-to-cloud, cloud-to-device),
    121         up to 4 KB of data. </li>
    122     </ul>
    123   </li>
    124   <li>Messaging (synchronous or asynchronous)
    125     <ul>
    126       <li>HTTP: Synchronous. 3rd-party app servers send messages as HTTP POST requests and
    127 wait for a response. This mechanism is synchronous and blocks the sender from sending
    128 another message until the response is received.</li>
    129       <li>XMPP (CCS): Asynchronous. 3rd-party app servers send/receive messages to/from all their
    130 devices at full line speed over persistent XMPP connections.
    131 XMPP (CCS) sends acknowledgment or failure notifications (in the
    132 form of special ACK and NACK JSON-encoded XMPP messages) asynchronously.</li>
    133     </ul>
    134   </li>
    135 
    136   <li>JSON
    137     <ul>
    138       <li>HTTP: JSON messages sent as HTTP POST.</li>
    139       <li>XMPP (CCS): JSON messages encapsulated in XMPP messages.</li>
    140     </ul>
    141   </li>
    142   <li>Plain Text
    143     <ul>
    144       <li>HTTP: Plain Text messages sent as HTTP POST.</li>
    145       <li>XMPP (CCS): Not supported.</li>
    146     </ul>
    147   </li>
    148   <li>Multicast downstream send to multiple registration IDs.
    149     <ul>
    150       <li>HTTP: Supported in JSON message format.</li>
    151       <li>XMPP (CCS): Not supported.</li>
    152     </ul>
    153   </li>
    154 </ul>
    155 
    156 
    157 <h2 id="send-msg">Sending Messages</h2>
    158 
    159 <p>This section gives an overview of sending messages. For details of message syntax,
    160 see <a href="{@docRoot}google/gcm/server-ref.html">Server Reference</a>.</p>
    161 
    162 <h3>Overview</h3>
    163 
    164 <p>Here is the general sequence of events that occurs when a 3rd-party application
    165 server sends a message (the details vary depending on the platform):</p>
    166 <ol>
    167   <li>The 3rd-party app server sends a message to GCM servers.</li>
    168   <li>The GCM connection server enqueues and stores the message if the device is offline.</li>
    169   <li>When the device is online, GCM connection server sends the message to the device.</li>
    170   <li>The client app processes the message. </li>
    171 </ol>
    172 
    173 <h3>Implement send request</h3>
    174 
    175 <p>The following sections describe the basic components involved in
    176 sending a request. See the <a href="{@docRoot}google/gcm/server-ref.html">Server Reference</a>
    177 for details.</p>
    178 
    179 <h4 id="target">Target</h4>
    180 <p>Required. When your app server sends a message in GCM, it must specify a target.</p>
    181 <p>For HTTP you must specify the target as one of the following:</p>
    182 <ul>
    183 <li><code>registration_ids</code>: For sending to 1 or more devices (up to 1000).
    184 When you send a message to multiple registration IDs, that is called a multicast message.</li>
    185 <li><code>notification_key</code>: For sending to multiple devices owned by a single user.</li>
    186 </ul>
    187 <p>For CCS (XMPP) you must specify the target as:</p>
    188 <ul>
    189 <li>{@code to}: This
    190 field may contain a single registration ID or a notification key.
    191 XMPP (CCS) does not support multicast messaging.</li>
    192 </ul>
    193 
    194 <h4 id="options">Options</h4>
    195 
    196 <p>There are various options the 3rd-party app server can set when sending a downstream
    197 message to a client app. See the <a href="{@docRoot}google/gcm/server-ref.html#table1">
    198 Server Reference</a> for details. Here are a few examples of possible options:</p>
    199 
    200 <ul>
    201   <li>{@code collapse_key}: whether a message should be "send-to-sync" or a "message with
    202 payload".</li>
    203   <li>{@code time_to_live}: setting an expiration date for a message.</li>
    204   <li>{@code dry_run}: Test your server.
    205 <p>If you want to test your request (either JSON or plain text) without delivering
    206 the message to the devices, you can set an optional HTTP parameter called
    207 <code>dry_run</code> with the value <code>true</code>. The result will be almost
    208 identical to running the request without this parameter, except that the message
    209 will not be delivered to the devices. Consequently, the response will contain fake
    210 IDs for the message and multicast parameters.</p>
    211 </li>
    212 </ul>
    213 
    214 <h4 id="payload">Payload</h4>
    215 <p>Optional. If you are including a payload in the message, you use the <code>data</code>
    216 parameter to include the payload. This applies for both HTTP and XMPP.</p>
    217 
    218 <p>See the <a href="{@docRoot}google/gcm/server-ref.html">Server Reference</a> for details on sending
    219 and receiving messages.</p>
    220 
    221 <h2 id="adv">Messaging Concepts and Best Practices</h2>
    222 
    223 <p>This section has a discussion of general messaging topics.</p>
    224 
    225 <h3 id="collapsible">Send-to-Sync  vs. Messages with Payload</h3>
    226 
    227 <p>Every message sent in GCM has the following characteristics:</p>
    228 <ul>
    229   <li>It has a payload limit of 4096 bytes.</li>
    230   <li>By default, it is stored by GCM for 4 weeks.</li>
    231 </ul>
    232 
    233 <p>But despite these similarities, messages can behave very differently depending
    234 on their particular settings. One major distinction between messages is whether
    235 they are collapsed (where each new message replaces the preceding message) or not
    236 collapsed (where each individual message is delivered). Every message sent in GCM
    237 is either a &quot;send-to-sync&quot; (collapsible) message or a &quot;message with
    238 payload&quot; (non-collapsible message).</p>
    239 
    240 <h4 id="s2s">Send-to-sync messages</h4>
    241 
    242 <p>A send-to-sync (collapsible) message is often a &quot;tickle&quot; that tells
    243 a mobile application to sync data from the server. For example, suppose you have
    244 an email application. When a user receives new email on the server, the server
    245 pings the mobile application with a &quot;New mail&quot; message. This tells the
    246 application to sync to the server to pick up the new email. The server might send
    247 this message multiple times as new mail continues to accumulate, before the application
    248 has had a chance to sync. But if the user has received 25 new emails, there's no
    249 need to preserve every &quot;New mail&quot; message. One is sufficient. Another
    250 example would be a sports application that updates users with the latest score.
    251 Only the most recent message is relevant. </p>
    252 
    253 <p>GCM allows a maximum of 4 different collapse keys to be used by the GCM server
    254 at any given time. In other words, the GCM server can simultaneously store 4
    255 different send-to-sync messages per device, each with a different collapse key.
    256 For example, Device A can have A1, A2, A3, and A4. Device B can have B1, B2, B3,
    257 and B4, and so on. If you exceed this number GCM will only keep 4 collapse keys, with no
    258 guarantees about which ones they will be.</p>
    259 
    260 <h3 id="payload">Messages with payload</h3>
    261 
    262 <p>Unlike a send-to-sync message, every &quot;message with payload&quot;
    263 (non-collapsible message) is delivered. The payload the message contains can be
    264 up to 4kb. For example, here is a JSON-formatted message in an IM application in
    265 which spectators are discussing a sporting event:</p>
    266 
    267 <pre class="prettyprint pretty-json">{
    268   "registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
    269   "data" : {
    270     "Nick" : "Mario",
    271     "Text" : "great match!",
    272     "Room" : "PortugalVSDenmark",
    273   },
    274 }</pre>
    275 
    276 <p>A &quot;message with payload&quot; is not simply a &quot;ping&quot; to the
    277 mobile application to contact the server to fetch data. In the aforementioned IM
    278 application, for example, you would want to deliver every message, because every
    279 message has different content. To specify a non-collapsible message, you simply
    280 omit the <code>collapse_key</code> parameter. Thus GCM will send each message
    281 individually. Note that the order of delivery is not guaranteed.</p>
    282 
    283 <p>GCM will store up to 100 non-collapsible messages. After that, all messages
    284 are discarded from GCM, and a new message is created that tells the client how
    285 far behind it is.</p>
    286 
    287 <p>The application should respond by syncing with the server to recover the
    288 discarded messages. </p>
    289 
    290 <h4 id="which">Which should I use?</h4>
    291   <p>If your application does not need to use non-collapsible messages, collapsible
    292 messages are a better choice from a performance standpoint. However, if you use
    293 collapsible messages, remember that <strong>GCM only allows a maximum of 4 different collapse
    294 keys to be used by the GCM server per registration ID at any given time</strong>. You must
    295 not exceed this number, or it could cause unpredictable consequences.</p>
    296 
    297 <h3 id="ttl">Setting an Expiration Date for a Message</h3>
    298 <p>You can use the <code>time_to_live</code> parameter in the send request
    299 to specify the maximum lifespan of a message.
    300 The value of this parameter must be a duration from 0 to 2,419,200 seconds, and
    301 it corresponds to the maximum period of time for which GCM will store and try to
    302 deliver the message. Requests that don't contain this field default to the maximum
    303 period of 4 weeks.</p>
    304 <p>Here are some possible uses for this feature:</p>
    305 <ul>
    306   <li>Video chat incoming calls</li>
    307   <li>Expiring invitation events</li>
    308   <li>Calendar events</li>
    309 </ul>
    310 <h4 id="bg">Background </h4>
    311 <p>GCM usually delivers messages immediately after they are sent. However,
    312 this might not always be possible. For example, if the platform is Android,
    313 the device could be turned off, offline, or otherwise unavailable.
    314 Or the sender itself might request
    315 that messages not be delivered until the device becomes active by using the
    316 <code>delay_while_idle</code> flag. Finally, GCM might intentionally delay messages
    317 to prevent an application from consuming excessive resources and negatively
    318 impacting battery life.</p>
    319 
    320 <p>When this happens, GCM will store the message and deliver it as soon as it's
    321 feasible. While this is fine in most cases, there are some applications for which
    322 a late message might as well never be delivered. For example, if the message is
    323 an incoming call or video chat notification, it will only be meaningful for a
    324 small period of time before the call is terminated. Or if the message is an
    325 invitation to an event, it will be useless if received after the event has ended.</p>
    326 
    327 <p>Another advantage of specifying the expiration date for a message is that GCM
    328 will never throttle messages with a <code>time_to_live</code> value of 0 seconds.
    329 In other words, GCM will guarantee best effort for messages that must be delivered
    330 &quot;now or never.&quot; Keep in mind that a <code>time_to_live</code> value of
    331 0 means messages that can't be delivered immediately will be discarded. However,
    332 because such messages are never stored, this provides the best latency for
    333 sending notifications.</p>
    334 
    335 <p>Here is an example of a JSON-formatted request that includes TTL:</p>
    336 <pre class="prettyprint pretty-json">
    337 {
    338   "collapse_key" : "demo",
    339   "delay_while_idle" : true,
    340   "registration_ids" : ["xyz"],
    341   "data" : {
    342     "key1" : "value1",
    343     "key2" : "value2",
    344   },
    345   "time_to_live" : 3
    346 },
    347 </pre>
    348 
    349 
    350 <h3 id="multi-senders">Receiving Messages from Multiple Senders</h3>
    351 
    352 <p>GCM allows multiple parties to send messages to the same application. For
    353 example, suppose your application is an articles aggregator with multiple
    354 contributors, and you want each of them to be able to send a message when they
    355 publish a new article. This message might contain a URL so that the application
    356 can download the article. Instead of having to centralize all sending activity in
    357 one location, GCM gives you the ability to let each of these contributors send
    358 its own messages.</p>
    359 
    360 <p>To make this possible, all you need to do is have each sender generate its own
    361 project number. Then include those IDs in the sender field, separated by commas,
    362 when requesting a registration. Finally, share the registration ID with your
    363 partners, and they'll be able to send messages to your application using their
    364 own authentication keys.</p>
    365 
    366 <p>Note that there is limit of 100 multiple senders.</p>
    367 
    368 <h3 id="lifetime">Lifetime of a Message</h3>
    369 
    370 <p>When a 3rd-party server posts a message to GCM and receives a message ID back,
    371 it does not mean that the message was already delivered to the device. Rather, it
    372 means that it was accepted for delivery. What happens to the message after it is
    373 accepted depends on many factors.</p>
    374 
    375 <p>In the best-case scenario, if the device is connected to GCM, the screen is on,
    376 and there are no throttling restrictions (see <a href="#throttling">Throttling</a>),
    377 the message will be delivered right away.</p>
    378 
    379 <p>If the device is connected but idle, the message will still be
    380 delivered right away unless the <code>delay_while_idle</code> flag is set to true.
    381 Otherwise, it will be stored in the GCM servers until the device is awake. And
    382 that's where the <code>collapse_key</code> flag plays a role: if there is already
    383 a message with the same collapse key (and registration ID) stored and waiting for
    384 delivery, the old message will be discarded and the new message will take its place
    385 (that is, the old message will be collapsed by the new one). However, if the collapse
    386 key is not set, both the new and old messages are stored for future delivery.
    387 Collapsible messages are also called <a href="#s2s">send-to-sync messages</a>.</p>
    388 
    389 <p class="note"><strong>Note:</strong> There is a limit on how many messages can
    390 be stored without collapsing. That limit is currently 100. If the limit is reached,
    391 all stored messages are discarded. Then when the device is back online, it receives
    392 a special message indicating that the limit was reached. The application can then
    393 handle the situation properly, typically by requesting a full sync.
    394 <br><br>
    395 Likewise, there is a limit on how many <code>collapse_key</code>s you can have for
    396 a particular device. GCM allows a maximum of 4 different collapse keys to be used
    397 by the GCM server per device
    398 any given time. In other words, the GCM server can simultaneously store 4 different
    399 send-to-sync messages, each with a different collapse key. If you exceed this number
    400 GCM will only keep 4 collapse keys, with no guarantees about which ones they will be.
    401 See <a href="#s2s">Send-to-sync messages</a> for more information.
    402 </p>
    403 
    404 <p>If the device is not connected to GCM, the message will be stored until a
    405 connection is established (again respecting the collapse key rules). When a connection
    406 is established, GCM will deliver all pending messages to the device, regardless of
    407 the <code>delay_while_idle</code> flag. If the device never gets connected again
    408 (for instance, if it was factory reset), the message will eventually time out and
    409 be discarded from GCM storage. The default timeout is 4 weeks, unless the
    410 <code>time_to_live</code> flag is set.</p>
    411 
    412 <p>Finally, when GCM attempts to deliver a message to the device and the
    413 application was uninstalled, GCM will discard that message right away and
    414 invalidate the registration ID. Future attempts to send a message to that device
    415 will get a <code>NotRegistered</code> error. See <a href="#unreg">
    416 How Unregistration Works</a> for more information.</p>
    417 <p>Although is not possible to track the status of each individual message, the
    418 Google Cloud Console stats are broken down by messages sent to device, messages
    419 collapsed, and messages waiting for delivery.</p>
    420 
    421 <h3 id="throttling">Throttling</h3>
    422 <p>To prevent abuse (such as sending a flood of messages to a device) and
    423 to optimize for the overall network efficiency and battery life of
    424 devices, GCM implements throttling of messages using a token bucket
    425 scheme. Messages are throttled on a per application and per <a href="#collapsible">collapse
    426 key</a> basis (including non-collapsible messages). Each application
    427 collapse key is granted some initial tokens, and new tokens are granted
    428 periodically therefter. Each token is valid for a single message sent to
    429 the device. If an application collapse key exhausts its supply of
    430 available tokens, new messages are buffered in a pending queue until
    431 new tokens become available at the time of the periodic grant. Thus
    432 throttling in between periodic grant intervals may add to the latency
    433 of message delivery for an application collapse key that sends a large
    434 number of messages within a short period of time. Messages in the pending
    435 queue of an application collapse key may be delivered before the time
    436 of the next periodic grant, if they are piggybacked with messages
    437 belonging to a non-throttled category by GCM for network and battery
    438 efficiency reasons.</p>
    439 
    440 
    441