Session
KeySession is the main entry point to the API. It connects an application to the platform and provides APIs for routing, subscribing, publishing and monitoring. This page describes the Session and discusses its configuration.
See JavaDoc for more details on KeySession.
Session Creation
Create a KeySession by configuring a KeySessionContext and using the KeySessionFactory.
The following sample shows the mandatory configuration that must be provided to connect an application to the platform.
KeySessionContext context = new KeySessionContext();
context.setApplicationName("<application-name>");
context.setKeyAccessUrl("https://<key-access-host>:6800");
context.setApiKey("<api-key>");
context.setTransportMode(TransportMode.TCP);
KeySession session = KeySessionFactory.create(context);
Registration
The first thing a session does is register with KeyAccess. The applicationName identifies the application and must match an application that has already been created and permissioned in KeyAccess, where the apiKey can also be found.
The keyAccessUrl points the session at KeyAccess. In highly available environments it can be a comma-separated list of URLs, the session will try each until registration succeeds.
The applicationVersion can be optionally set. It allows monitoring dashboards to show which version of the application is running.
Transport
transportMode controls how application messages reach the platform, there are two options:
TransportMode.IPC_UDP - offers the best performance. Use this when applications are deliberately deployed alongside the platform and are able to use the same IPC/UDP transport setup as the platform. The ipcUdpDir must also be set to share the same directory that is configured for platform use.
context.setTransportMode(TransportMode.IPC_UDP);
context.setIpcUdpDir("<ipc-udp-directory>");
TransportMode.TCP - allows connectivity via a TCP proxy for applications that do not have direct access to the KeySquare platform, e.g. connecting from a local workstation to a remote deployment.
context.setTransportMode(TransportMode.TCP);
The transportInterface can be set to bind traffic to a specific network interface.
Session Listener
When creating a session, a KeySessionListener can also be provided to receive session lifecycle events and unexpected errors.
KeySessionListener listener = new KeySessionListener() {
@Override
public void connected(boolean isFirstConnect) {
log.info("Connected, firstConnect={}", isFirstConnect);
}
@Override
public void disconnected() {
log.warn("Disconnected");
}
@Override
public void onError(Throwable throwable) {
log.error("Unexpected session error", throwable);
}
};
KeySession session = KeySessionFactory.create(context, listener);
All listener methods are optional. Only override the callbacks the application needs.
See JavaDoc for more details on KeySessionListener.
Lifecycle and Reconnect
A session reconnects automatically by default if it becomes disconnected from transport. When it reconnects, it reapplies the application's ongoing subscriptions.
| Option | Default | Description |
|---|---|---|
autoReconnect | true | Controls whether the session keeps trying to reconnect after a disconnect. |
autoReconnectApplySubscriptions | true | Controls whether application subscriptions are re-applied after reconnect. Disable this only if the application wants to rebuild subscriptions itself. |
The listener receives connected(boolean isConnected) where isConnected is true on the first connection and false on subsequent connections.
Recovery Policy
The Recovery Policy deals with the data the application has already published.
The API can keep a publication cache containing the latest published message for each topic. After a reconnect, the configured recoveryPolicy decides whether those cached messages should be republished.
| Policy | Behaviour |
|---|---|
RecoveryPolicy.REPUBLISH_ALL | Default behaviour. Republish the latest cached message for every topic. |
RecoveryPolicy.REPUBLISH_ALL_IF_PRIMARY | Republish only if this application instance is PRIMARY. This is useful for active/standby applications. See Resiliency for details on leadership. |
RecoveryPolicy.IGNORE | Do nothing. Use this for applications that manage recovery themselves. |
See JavaDoc for more details on RecoveryPolicy.
Cache Control
Messages which are marked with the CacheMode.DO_NOT_CACHE will not be stored in the publication cache and therefore will not be republished on reconnection - this flag also impacts whether the message is stored by the Relay Cache.
message.cacheMode(CacheMode.DO_NOT_CACHE);
A voided publication removes the cached value for that topic:
message.voided(true);
Recovery is focused on the latest live image for each topic, not every event that the application has published.
Custom Recovery Policy
Applications with specialised failover rules can provide a custom RecoveryPolicy.
RecoveryPolicy primaryOrSecondary = new RecoveryPolicy() {
@Override
public boolean requiresPublicationCache() {
return true;
}
@Override
public void onRecovery(RecoveryContext context, RecoveryActions actions) {
LeadershipState leadershipState = context.leadershipState();
if (leadershipState == LeadershipState.PRIMARY || leadershipState == LeadershipState.SECONDARY) {
actions.republishAll();
}
}
};
context.setRecoveryPolicy(primaryOrSecondary);
Return true from requiresPublicationCache() only when the policy may call republishAll().
Performance Tuning
The KeySessionContext has the following settings that can be tuned.
| Option | Description |
|---|---|
eventLimit | Maximum number of messages processed in one session duty cycle. Higher values can improve throughput; lower values can reduce time spent in a single cycle. |
idleStrategySupplier / idleStrategy | Controls how the session thread waits for work. Busy strategies can reduce latency but will use a CPU core. |
cpus | Pins the session thread to specific CPUs when the host has reserved cores for the application. |
concurrencyMode | Defaults to CONCURRENT. EXCLUSIVE mode is available, which allows the API internals to use reduced locking, however all interactions with the session must be performed on the session thread itself. |
Transport buffers can also be tuned:
| Option | Description |
|---|---|
tcpBufferSize | Buffer size used in TCP mode. |
ipcUdpTermBufferLength | Application traffic buffer size used in IPC_UDP mode. |
ipcUdpAdminTermBufferLength | Session control and monitoring buffer size used in IPC_UDP mode. |
The buffer sizes must all be positive powers of two.
Custom Codec
| Option | Description |
|---|---|
customCodec | Codec used for Custom messages. See Custom Codec. |
Advanced Options
These options are for specialised use cases. These should only be used when directed by KeySquare support.
| Option | Description |
|---|---|
relayAffinityTag | Allows for load balancing of subscriptions across relays. |
flags | Experimental feature flags. |